{"id":11707,"library":"react-flatten-children","title":"React Children Flattener","description":"`react-flatten-children` is a lightweight React utility library designed to resolve challenges associated with React Fragments when processing component children. In React, fragments (`<></>` or `<React.Fragment>`) group multiple children but are treated as single children by their parent, which can disrupt components expecting direct access to all child elements (e.g., `react-router`'s `Switch` component looking for `Route` children). This package offers a single function, `flattenChildren`, which recursively traverses a component's `children` prop, extracts all valid React elements, and returns them as a flat array. This effectively \"unwraps\" fragments, ensuring all nested children are accessible. The current stable version is 1.1.2, with recent updates primarily adding TypeScript support in v1.1.0. Its primary value lies in simplifying child manipulation for library authors and application developers alike, preventing common issues where fragment usage can lead to unexpected component behavior or errors during child introspection. It helps maintain compatibility with user expectations of flexible fragment usage within component APIs.","status":"active","version":"1.1.2","language":"javascript","source_language":"en","source_url":"https://github.com/gregberge/react-flatten-children","tags":["javascript","react","utility","children","flatten","fragment","typescript"],"install":[{"cmd":"npm install react-flatten-children","lang":"bash","label":"npm"},{"cmd":"yarn add react-flatten-children","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-flatten-children","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"'flattenChildren' is the default export of the library. Attempting to destructure it as a named import will result in 'undefined'.","wrong":"import { flattenChildren } from 'react-flatten-children';","symbol":"flattenChildren","correct":"import flattenChildren from 'react-flatten-children';"},{"note":"This is the CommonJS import pattern suitable for Node.js environments or older build systems.","symbol":"flattenChildren (CJS)","correct":"const flattenChildren = require('react-flatten-children');"},{"note":"TypeScript type definitions, including the 'FlatChildren' type for the returned array, were officially added in v1.1.0. Prior versions required manual type declarations.","symbol":"FlatChildren (TypeScript Type)","correct":"import flattenChildren, { FlatChildren } from 'react-flatten-children';\n\nfunction MyComponent({ children }: { children: React.ReactNode }) {\n  const flatChildren: FlatChildren = flattenChildren(children);\n  // flatChildren is now typed as ReactElement[]\n}"}],"quickstart":{"code":"import React from 'react';\nimport { Switch as BaseSwitch, Route, Redirect } from 'react-router';\nimport flattenChildren from 'react-flatten-children';\n\n// Imagine these are your page components\nconst PublicHome = () => <div>Public Home</div>;\nconst PrivateHome = () => <div>Private Home</div>;\nconst Account = () => <div>Account Page</div>;\nconst Login = () => <div>Login Page</div>;\nconst About = () => <div>About Page</div>;\n\n// Create a fragment-ready Switch component that can handle nested fragments\nconst Switch = ({ children }) => (\n  <BaseSwitch>{flattenChildren(children)}</BaseSwitch>\n);\n\nconst Routes = ({ isLoggedIn }) => (\n  <Switch>\n    {isLoggedIn ? (\n      <>\n        <Route exact path=\"/\" component={PrivateHome} />\n        <Route path=\"/account\" component={Account} />\n      </>\n    ) : (\n      <>\n        <Route exact path=\"/\" component={PublicHome} />\n        <Route path=\"/login\" component={Login} />\n      </>\n    )}\n    <Route path=\"/about\" component={About} />\n    <Redirect to=\"/\" />\n  </Switch>\n);\n\nexport default Routes;","lang":"javascript","description":"This example demonstrates how to use `flattenChildren` to make a `react-router` Switch component compatible with React Fragments, allowing routes to be conditionally grouped within fragments."},"warnings":[{"fix":"Always pass children through `flattenChildren(children)` before processing them to ensure a flat array of all nested elements, enabling proper child introspection.","message":"When building components that introspect or iterate over their children (e.g., React Router's Switch or a custom tab component), React Fragments (<>...</> or <React.Fragment>...</React.Fragment>) are treated as single children. This prevents the parent component from directly accessing the elements nested inside the fragment, leading to unexpected rendering or logic failures if the component expects a flat list of specific child types.","severity":"gotcha","affected_versions":">=1.0.0 (applies to all React versions where fragments exist)"},{"fix":"Upgrade to `react-flatten-children@^1.1.0` or newer to leverage official, built-in TypeScript types, improving type safety and developer experience.","message":"Earlier versions of `react-flatten-children` (prior to v1.1.0) did not include native TypeScript type definitions. Developers using TypeScript would have needed to create their own declaration files or use type assertions, which could lead to type safety issues or additional maintenance overhead.","severity":"gotcha","affected_versions":"<1.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use `const flatChildren: ReactElement[] = flattenChildren(children);` to correctly type the flattened output as an array of React elements.","cause":"In TypeScript, the `children` prop has a broad type (`ReactNode`) that includes fragments, `null`, `undefined`, etc. Direct assignment or iteration expecting `ReactElement[]` will fail if fragments are present.","error":"Type 'ReactNode' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>[]'."},{"fix":"Apply `flattenChildren(children)` to the children prop before passing it to the component that expects a flat list of direct children, like `<Switch>{flattenChildren(children)}</Switch>`.","cause":"A component expects a single direct child, but it receives a React Fragment which contains multiple children, or it receives a fragment when it expects a specific element type directly.","error":"Error: `Router` may have only one child element at `Switch` (from React Router or similar libraries)"}],"ecosystem":"npm"}