I know my title is quite weird. but allow me explain this first.
const alter = (currentFloor: number) => {
if (overallState.startFloor === '' || overallState.endFloor === '')
return {}
if (
Number(overallState.startFloor) <= currentFloor &&
Number(overallState.endFloor) >= currentFloor
) {
return { selectedKey: overallState.state }
}
return {}
}
/* ... */
return({
randomArray.map((e,index)=>(
<Dropdown
placeholder="placeholder"
options={someoptions}
{...alter(index)} // how does it works????
/>
))
})
I have a function which returns object have prop of fluent UI conditionally.
as you can see, function alter returns object or undefined. but still, it is function.
I never heard about I can spread function itself in curly braces.
These codes work as I intended. but I have no idea how it works.
Can you please ask me what happened in these codes? Thanks.
CodePudding user response:
These are fundamendals of how react translates JSX to its own code. Basicaly if you write
<Dropdown
placeholder="placeholder"
options={someoptions}
/>
Jsx will be translated to something like
React.createElement('Dropdown', {placeholder: "placeholder, options: someOptions})
if you use spread syntax like in your code
<Dropdown
placeholder="placeholder"
options={someoptions}
{...alter(index)} // how does it works????
/>
it will be same as
React.createElement('Dropdown', {placeholder: "placeholder", options: someOptions, ...alter(index)})
and this works, because alter(index)
function is called, which javascript simply see as given returned object which can be something like { selectedKey: overallState.state }
whis is the same as
React.createElement('Dropdown', {placeholder: "placeholder", options: someOptions, ...{ selectedKey: overallState.state }})
which becomes
React.createElement('Dropdown', {placeholder: "placeholder", options: someOptions, selectedKey: overallState.state })
and transformed back in JSX
<Dropdown
placeholder="placeholder"
options={someoptions}
selectedKey={overallState.state}
/>
its work just like basic spread syntax of object in function parameters.
CodePudding user response:
you can spread the return value of a function in curly braces. not function itself.
in this case, your function will run first and return an object. then that object will spread.
{...alter(index)} -> { ...{ selectedKey: overallState.state } or {}} -> {selectedKey: overallState.state}
Hope you understand.