Skip to content

React utility to flatten fragments ๐Ÿ—œ

License

Notifications You must be signed in to change notification settings

gregberge/react-flatten-children

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

16 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

react-flatten-children

License npm package Build Status DevDependencies

React utility to flatten fragments ๐Ÿ—œ

npm install react-flatten-children

Example

import React from "react";
import { Switch as BaseSwitch } from "react-router";
import flattenChildren from "react-flatten-children";
import PublicHome from "./PublicHome";
import PrivateHome from "./PrivateHome";
import Account from "./Account";
import Login from "./Login";

// Create a fragment ready Switch
const Switch = ({ children }) => (
  <BaseSwitch>{flattenChildren(children)}</BaseSwitch>
);

const Routes = ({ isLoggedIn }) => (
  <Switch>
    {isLoggedIn ? (
      <>
        <Route exact path="/" component={PrivateHome} />
        <Route path="/account" component={Account} />
      </>
    ) : (
      <>
        <Route exact path="/" component={PublicHome} />
        <Route path="/login" component={Login} />
      </>
    )}
    <Route path="/about" component={About} />
    <Redirect to="/" />
  </Switch>
);

export default Routes;

๐Ÿ‘‰ Checkout an interactive example on CodeSandbox

Why?

In many cases you have to introspect children, it can be to use the first route matching a path, extract the label of a tab, or another use case.

React considers fragments as children, even if it is in fact a group of children. This package flattens children and makes your component API compatible with fragments. Users expect your library to be compatible with fragments. If you want to avoid tons of issues (see remix-run/react-router#5917, remix-run/react-router#5785), you should use it!

License

MIT