From b28cc59c861057f26f577845bd4d224f064b88d9 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 12 Mar 2018 20:43:16 -0500 Subject: [PATCH] Add Mapping Over One Or Many Children as a react til --- README.md | 3 ++- react/mapping-over-one-or-many-children.md | 29 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 react/mapping-over-one-or-many-children.md diff --git a/README.md b/README.md index e41acf2..b83224f 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/react/mapping-over-one-or-many-children.md b/react/mapping-over-one-or-many-children.md new file mode 100644 index 0000000..b7b56a0 --- /dev/null +++ b/react/mapping-over-one-or-many-children.md @@ -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.Children.map(children || null, (child, i) => { + return ; + })} + + ); +}; +``` + +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).