Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-keyed-flatten-children

grrowl947.7kMIT5.0.0TypeScript support: included

Flattens React children and fragments to an array with predictable and stable keys

react, fragment, flatten, children, utility

readme

react-keyed-flatten-children

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 nested arrays and React.Fragments into a regular, one-dimensional array while ensuring element and fragment keys are preserved, unique, and stable between renders.

getting started

This library requires a version of react-is matching your React version be installed alongside this library as a peer dependency. So, if you're using React 19:

npm install react-keyed-flatten-children react-is@19

If you're using React 18 or lower:

npm install react-keyed-flatten-children react-is@18

why?

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 it was decided against since "React.Children is in maintenance mode" until a better solution is devised.

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 Children.toArray.

import flattenChildren from "react-keyed-flatten-children";

const MenuList = ({ children }) => {
  const [selectedKey, setSelectedKey] = useState(null);

  return (
    <div role="menu">
      {flattenChildren(props.children).map(child => {
        if (child.type === MenuItem) {
          return React.cloneElement(child, {
            selected: child.key === selectedKey,
            onClick: () => setSelectedKey(child.key)
          });
        }
        return child;
      })}
    </div>
  );
};

Now consumers can use arrays, fragments, or conditionally render items and your library will continue to work predictably.

<MenuList>
  <h2>Animals</h2>
  <MenuItem>Dogs</MenuItem>
  <MenuItem>Cats</MenuItem>

  <h2>Cars</h2>
  {CARS_ARRAY.map(car => (
    <MenuItem>{car}</MenuItem>
  ))}

  {isLoggedIn() && (
    <>
      <h2>User</h2>
      <MenuItem>You!</MenuItem>
      <MenuItem>Someone else!</MenuItem>
    </>
  )
</MenuList>

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>{flattenChildren(children)}</Switch>
);

const AppRoutes = ({ user }) => (
  <Router>
    <GlobalNavigation user={user} />
    <FlexibleSwitch>
      <Route path="/about">
        <About />
      </Route>
      {user && (
        <>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/settings">
            <Settings />
          </Route>
        </>
      )}
      <Route path="/">
        <Home />
      </Route>
    </FlexibleSwitch>
  </Router>
);

license

MIT

changelog

5.0.0

Move react-is to a peer dependency so we can support all react versions in a single version. (thanks @imjordanxd!)

4.0.0

React 19 support! (thanks for the help @bmv437, @benface)

3.2.0

Revert react-is bump, since it breaks React 18! Sorry!

Fix to README.md example (thanks @nilportugues)

3.1.0

Bump react-is to fix React 19 compatability

3.0.2

Bump braces from 3.0.2 to 3.0.3

Migrate yarn.lock to package-lock.json

3.0.1

Bump micromatch from 4.0.5 to 4.0.8

3.0.0

Convert to ESM by default.

Transpile to ES2015.

CommonJS now uses module.exports rather than exports.default. This allows for importing in CommonJS without requiring explicit default. e.g.

// Previous:
const flattenChildren = require("react-keyed-flatten-children");
flattenChildren.default(children);
// Now:
const flattenChildren = require("react-keyed-flatten-children");
flattenChildren(children);

(thanks @will-stone)

2.2.1

Removed invalid key types from package.json (thanks @imjordanxd)

2.2.0

Fix issue with build, dist/ wasn't included with the ESM change (thanks @imjordanxd)

Fix Typescript version in CHANGELOG (thanks @rnestler)

Adds Node v20 support (CI coverage)

2.1.0

Now using React 18.2.0 and Typescript 5.0.4. If this change effects your application, depend directly on 2.0.0

2.0.0

BREAKING: Package is now ESM-compatible (thanks @imjordanxd!)

Bumps a number of deep dependencies with security issues

1.2.0

Removes index.ts from the distributed package

1.1.0

Avoid adding an extra first period to the keys at the zero depth (what was ..$apple is now .$apple)

1.0.0

Initial release