DEV Community

Cover image for Passing props using the spread operator in React
Arika O
Arika O

Posted on • Updated on

Passing props using the spread operator in React

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:

Alt Text

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:

Alt Text

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:

Alt Text

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:

Alt Text

And our child component will access the properties of that object like this:

Alt Text

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

Top comments (3)

Collapse
 
starpebble profile image
starpebble

Keep going! Don't give up on inlining.

const ExampleComponentName = ({hStyle, pStyle, name}) => {
  // code
}
Enter fullscreen mode Exit fullscreen mode

Does this look like what you want?

Collapse
 
vishnubaliga profile image
Vishnu Baliga

Well written ! :)

Collapse
 
arikaturika profile image
Arika O

Thx, hope it helped!