Reputation: 8971
I am familiar with JavaScript spread syntax:
obj1 = {x: 1, y: 2, z: 3 }
obj2 = {...obj1}
console.log(JSON.stringify(obj1) == JSON.stringify(obj2)) // true
In React's JSX syntax I often see what looks like spread syntax:
props = {x: 1, y: 2, z: 3}
<SomeComponent {...props} />
Which I know translates into roughly
SomeComponent({x: 1, y: 2: z: 3})
Which is essentially props drilling. HOWEVER, I also know that JSX allows for specifying JavaScript expressions in curly brackets. But NOT, apparently, as property specifications? It seems then that the mechanism for props drilling (i.e. specifying curly brackets in a JSX element definition - <X {...props} />
vs <X something={js expression} />
), although it looks like a regular spread operation, it is actually not?
Writing this out I'm more confident that this is the case... But I would like feedback if I'm wrong!
Upvotes: 1
Views: 391
Reputation: 42566
Yes, you are right. However, you shouldn't blindly use the spread syntax to pass the entire set of props from the parent component to the child component, as this will result in the following warning:
Warning: Invalid value for prop `someProp` on <some> tag
Therefore, you should only pass down props you require. You can still use the spread syntax for that purpose.
For instance, if the child SomeComponent only accept y
and z
for props,
const { x, ...otherProps } = props;
return <SomeComponent {...otherProps} />
Upvotes: 1
Reputation: 759
Your intuition is right : even if the syntax is the same, the "spread attributes" syntax is a JSX feature, as defined here by Sebastian Markbåge (React core team) https://gist.github.com/sebmarkbage/07bbe37bc42b6d4aef81#jsx-spread-attributes
An observation about vocabulary : "drilling" props is usually a negative term, meaning that you are passing down props through an excessive amount of components, and is usually a code smell. A more neutral term would be "passing" props.
Upvotes: 2