positivelyzack avatar

Adding props or functionality to React children

positivelyzack

Published: 02 Jan 2019 › Updated: 02 Jan 2019Adding props or functionality to React children

Adding props or functionality to React children

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).

Leave Adding props or functionality to React children to:

Written by

Founder and Full-stack Developer Instructor

Read more #react posts


Best Posts From positivelyzack

We have not curated any of positivelyzack's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From positivelyzack