Skip to content
Advertisement

How to pass props to {this.props.children}

I’m trying to find the proper way to define some components which could be used in a generic way:

JavaScript

There is a logic going on for rendering between parent and children components of course, you can imagine <select> and <option> as an example of this logic.

This is a dummy implementation for the purpose of the question:

JavaScript

The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children?

Advertisement

Answer

Cloning children with new props

You can use React.Children to iterate over the children, and then clone each element with new props (shallow merged) using React.cloneElement.

See the code comment why I don’t recommend this approach.

JavaScript
JavaScript

Calling children as a function

Alternatively, you can pass props to children via render props. In this approach, the children (which can be children or any other prop name) is a function which can accept any arguments you want to pass and returns the actual children:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement