Passing props using the spread operator in React
Arika O
Posted on May 3, 2020
In React, passing props from parent to children components and using them is pretty straight forward. Let's say we have a parent component called App
which renders a child component called ExampleComponentDate
. The child component will display a date we set in the parent component, so to be able to use it, it needs to get it from one level up (in this case) through props. You can see this happening in the example below:
But what if we want, for example, to render a second child component and apply certain CSS styles to it? Let's imagine our styles are stored inside multiple variables in the parent and we want to use them inside the second child. Let's call it ExampleComponentName
. We pass our props like so:
And our child component will use them like in the code below. I am using destructuring to get the individual props so we can get rid of the props.
notation:
We can easily see that the more props we want to pass, the messier the code becomes. The firs example that came into my head was the CSS styles example but our variables can virtually contain anything we want. What we could do instead is store all the styles in an object and pass it from parent to child using the spread operator
. Like so:
And our child component will access the properties of that object like this:
I sometimes use this method for passing props but I'm not a big fan of it. It's not always obvious what the props we're passing have inside. This means we need to further inspect the code plus it can lead to unnecessary complexity when debugging. It is, nevertheless, very useful when children components need lots of props but we do not want to pass them one by one.
Image source: Christina Morillo/@divinetechygirl on Pexels
Posted on May 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 7, 2022