1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Mapping Over One Or Many Children as a react til

This commit is contained in:
jbranchaud
2018-03-12 20:43:16 -05:00
parent 3f65c93b60
commit b28cc59c86
2 changed files with 31 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_638 TILs and counting..._
_639 TILs and counting..._
---
@@ -447,6 +447,7 @@ _638 TILs and counting..._
- [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md)
- [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md)
- [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md)
- [Mapping Over One Or Many Children](react/mapping-over-one-or-many-children.md)
- [Passing Props Down To React-Router Route](react/passing-props-down-to-react-router-route.md)
- [Proxy To An API Server In Development With CRA](react/proxy-to-an-api-server-in-development-with-cra.md)
- [Quickly Search For A Component With React DevTools](react/quickly-search-for-a-component-with-react-devtools.md)

View File

@@ -0,0 +1,29 @@
# Mapping Over One Or Many Children
In [Dynamically Add Props To A Child
Component](https://github.com/jbranchaud/til/blob/master/react/dynamically-add-props-to-a-child-component.md),
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.
```javascript
const ParentWithClick = ({ children }) => {
return (
<React.Fragment>
{React.Children.map(children || null, (child, i) => {
return <child.type {...child.props} key={i} onClick={handleClick} />;
})}
</React.Fragment>
);
};
```
The [`React.Children.map`
function](https://reactjs.org/docs/react-api.html#reactchildrenmap) allows
mapping over one or many elements and if `children` is `null` or
`undefined`, it will return `null` or `undefined` respectively.
See a [live example here](https://codesandbox.io/s/kwj29y2j2r).