HomeTutorsContact
ReactJS
How to pass all props from parent to child component in React?
Gulshan Saini
June 30, 2020
1 min

Props can be passed from parent to child components explicitly as attributes or using spread operator ... in JSX

Let’s explore both the ways. To begin the tutorial we have created following App and Image components

App Component

In App component we have array of images. The properties of individual image is passed to Image component as props.

Image Component

The Image component destructure the props passed from parent App component and render the figure element by consuming those properties.

Passing props as attributes on JSX

One way of passing props from parent to child component is by defining attributes on child components JSX. As we can see in App component, we are reading the images array and passing the individual image properties in Image component JSX as follows

Now, the src, alt, width, height, and source attributes will be passed to <Image> component as props and can be accessed in child components as follows by destructuring props

Passing props using spread operator on JSX

Another clean way of passing props to child components is using spread operator on JSX. So, the updated code in App component would look like

Still, the src, alt, width, height, and source attributes will be passed to <Image> component as earlier.

As you can see the code is more clean now and easy to read. Another benefit is if, I introduce a new property in images array for all items, it will automatically get passed to child component without any changes in JSX however, changes would be required in child component to render that new property.

Their are few things before you should consider passing whole props to child components

  • You are passing lot of information to child component even when its not required. You should still validate in child components that required props are passed or not otherwise you may accidentally break component.
  • More props means more things will cause component to render.

Tags

#react
Previous Article
How to extract deeply nested property in JavaScript(ES6)?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to set dynamic inner text with React.createElement()?
July 19, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media