Adding props or functionality to React children

Words
117
Reading
1 min
Listen
Play
8y

For most cases to render children you can use this.props.children

render() {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }

However, if you wanted to add functionality like an onClick handler to the children you can map through the children and clone them with the extra props.

Let's say you start with this:

render() {   
    return(
            <ShoppingList>
              <Item>First</Item>
              <Item>Second</Item>
              <Item>Third</Item>
            </Shopping>   
    ) 
}

And you wanted to add an onclick to each item. Then you can use React.Children.map API and add it to each child using the React.cloneElement React API. Note the React.Children.map works differently than a typical ES6 .map. As its first argument it takes in the array that it will map through and the 2nd argument is the function applied to each element.

render() {
        return (
          <div>
          {React.Children.map(this.props.children, child => {
            return React.cloneElement(child, {
              onClick: this.props.onClick })   
         })}
         </div>
       ) 
}

The arguments in the function applied to each element are (the_children_element, the_props_you_want_to_add_to_it).

Adding props or functionality to React children | Ecency