Passing props using the spread operator in React

arikaturika

Arika O

Posted on May 3, 2020

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

💖 💪 🙅 🚩
arikaturika
Arika O

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

Dark Mode Guy
javascript Dark Mode Guy

April 20, 2023

Infinite-Scroll And GitHub REST API
javascript Infinite-Scroll And GitHub REST API

November 22, 2022

Keeping tabs on Bitcoin
javascript Keeping tabs on Bitcoin

November 12, 2022

Javascript var, let, const difference
javascript Javascript var, let, const difference

September 3, 2022