Similar to React's built-in
Children.toArray method, this utility takes children and returns them as an array for introspection or filtering. Different from
Children.toArray, it will flatten arrays and
React.Fragments into a regular, one-dimensional array while ensuring element and fragment keys are preserved, unique, and stable between renders.
npm install react-keyed-flatten-children
yarn add react-keyed-flatten-children
From the documentation of Children.toArray:
[toArray] returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
Unfortunately it has some thorny edges:
- Children.toArray does not traverse into fragments, which limits flexibility of its use.
- Existing solutions exist, but they do not preserve the keys of the children and fragments, which throws away valuable performance optimisations provided through React keys.
- You're might be doing something a little wild, so you want the concept of "children" to as predictable as possible for you, and for the consumers of your library or component, to avoid issues like this down the line.
Some have proposed, soon after Fragments were introduced, that a built-in
React.Children.toFlatArray would be useful, but
View the codesandbox here to get hands-on with how and when to utilise this module.
for using this in your app
I've written a more application-focussed explanation in my article "Addressing Children.toArray's thorny edges".
for library authors
In most cases
react-keyed-flatten-children is a drop-in replacement for
import flattenChildren from "react-keyed-flatten-children";const MenuList = childrenconst selectedKey setSelectedKey = ;return<div ="menu"></div>;;
Now consumers can use arrays, fragments, or conditionally render items and your library will continue to work predictably.
for everyone else
Work around libraries which don't support fragments passed into children.
import flattenChildren from "react-keyed-flatten-children";import Switch Route from "react-router";// A <Switch> looks through its children <Routes>, but won't match <Routes> within fragments.// <FlexibleSwitch> will flatten out its children so <Switch> is able to see all children.const FlexibleSwitch = children<Switch></Switch>;const AppRoutes = user<Router><GlobalNavigation = /><Switch><Route ="/about"><About /></Route>user &&<><Route ="/users"><Users /></Route><Route ="/settings"><Settings /></Route></><Route ="/"><Home /></Route></Switch></Router>;