Categories
React Answers

How to pass props to this.props.children with React?

Spread the love

To pass props to this.props.children with React, we call the React.cloneElement method.

For instance, we write

<div>
  {React.cloneElement(this.props.children[0], {
    loggedIn: true,
    testPropB: true,
  })}
  {React.cloneElement(this.props.children[1], {
    loggedIn: true,
    testPropA: false,
  })}
</div>;

to call cloneElement with the child element to render and an object with thge props that we want to pass into the child component.

We pass the loggedIn and testPropB props to the this.props.children[0] component.

And we pass the loggedIn and testPropA props to the this.props.children[1] component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *