Monday 30 January 2017

reactjs - What is this prop syntax in my component?

Answer


Answer





I have the following code:




const cEditor = (onUpdate, props) => ();


What is being done by {...props}? It seems as if it is passing down props to the component. What does this syntax mean?


Answer



That's using spread syntax to "spread" the props to the component. Per the React documentation:




Spread Attributes




If you already have props as an object, and you want to pass it in JSX, you can use ... as a "spread" operator to pass the whole props object. These two components are equivalent:



function App1() {
return ;
}

function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return ;
}



Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.




So, if you have an object with props as keys and the prop values as values, you can use spread syntax to spread them to the component. These two components are the same:



const props = {
a: 5,
b: "string"

}



Is the same as:






In your case, props in the function cEditor is an object will all the props and prop values as keys and values respectively. Then, those props and prop values are passed to the , except for onUpdate, that is passed separately

(but is overridden if props has an onUpdate key and value).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...