react-flatten-children
React utility to flatten fragments 🗜
npm install react-flatten-children
Example
;;;;;;; // Create a fragment ready Switchconst Switch = <BaseSwitch></BaseSwitch>; const Routes = <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>; ;
👉 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 https://github.com/ReactTraining/react-router/issues/5917, https://github.com/ReactTraining/react-router/issues/5785), you should use it!
License
MIT