项目作者: gregberge

项目描述 :
React utility to flatten fragments 🗜
高级语言: TypeScript
项目地址: git://github.com/gregberge/react-flatten-children.git
创建时间: 2018-10-01T19:56:22Z
项目社区:https://github.com/gregberge/react-flatten-children

开源协议:MIT License

下载


react-flatten-children

License
npm package
Build Status
DevDependencies

React utility to flatten fragments 🗜

  1. npm install react-flatten-children

Example

  1. import React from "react";
  2. import { Switch as BaseSwitch } from "react-router";
  3. import flattenChildren from "react-flatten-children";
  4. import PublicHome from "./PublicHome";
  5. import PrivateHome from "./PrivateHome";
  6. import Account from "./Account";
  7. import Login from "./Login";
  8. // Create a fragment ready Switch
  9. const Switch = ({ children }) => (
  10. <BaseSwitch>{flattenChildren(children)}</BaseSwitch>
  11. );
  12. const Routes = ({ isLoggedIn }) => (
  13. <Switch>
  14. {isLoggedIn ? (
  15. <>
  16. <Route exact path="/" component={PrivateHome} ></Route>
  17. <Route path="/account" component={Account} ></Route>
  18. </>
  19. ) : (
  20. <>
  21. <Route exact path="/" component={PublicHome} ></Route>
  22. <Route path="/login" component={Login} ></Route>
  23. </>
  24. )}
  25. <Route path="/about" component={About} ></Route>
  26. <Redirect to="/" ></Redirect>
  27. </Switch>
  28. );
  29. 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 https://github.com/ReactTraining/react-router/issues/5917, https://github.com/ReactTraining/react-router/issues/5785), you should use it!

License

MIT