npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-keyed-flatten-children

v3.0.2

Published

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

Downloads

679,644

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 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

npm install react-keyed-flatten-children
yarn add react-keyed-flatten-children

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} />
    <Switch>
      <Route path="/about">
        <About />
      </Route>
      {user && (
        <>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/settings">
            <Settings />
          </Route>
        </>
      )}
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  </Router>
);

license

MIT