til/mapping-over-one-or-many-children.md at master · jbranchaud/til · GitHub

Mapping over one or more children in #Reactjs

  • In Dynamically Add Props To A Child Component, I talked about how a child element can be reconstituted with additional props.
  • The approach I showed will only work in the case of a single child being nested in that component.
  • What if you want your component to account for one, many, or even children?
  • React comes with a built-in function for mapping that handles these cases.
  • The function allows mapping over one or many elements and if is or , it will return or respectively.

GitHub is where people build software. More than 27 million people use GitHub to discover, fork, and contribute to over 80 million projects.

We recommend upgrading to the latest Safari, Google Chrome, or Firefox.

In Dynamically Add Props To A Child Component, I talked about how a child element can be reconstituted with additional props. The approach I showed will only work in the case of a single child being nested in that component. What if you want your component to account for one, many, or even children?

React comes with a built-in function for mapping that handles these cases.

const ParentWithClick = ({ children }) => { return ( < React.Fragment > {React.Children.map(children || null, (child, i) => { return < child.type {... child.props} key={i} onClick={handleClick} / >; })} < / React.Fragment > ); };

respectively.

See a live example here.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

til/mapping-over-one-or-many-children.md at master · jbranchaud/til · GitHub