Using Fragments inside Switch
See original GitHub issueReact 16.2 added the concept of Fragments. I would like to be able to use Fragments inside Switch components to do things like this:
<Switch>
<>
<Route path="/" />
<Route path="/about" />
</>
<>
<Route path="/messages" />
<Route path="/messages/new" />
</>
</Switch>
The application I am working on is composed by small modules and all those small modules are composed together in a single app based on some conditions. Since routes need to be direct children of Switch those small modules need to expose routes as an array. However using fragments would make it a lot simpler and more readable.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:15 (9 by maintainers)
Top Results From Across the Web
Redirect doesn't work inside Switch when Fragment has been ...
Fragment that has been used inside Switch . Redirection works fine when it's removed.
Read more >React Router Switch + Fragments example - CodeSandbox
React Router Switch + Fragments example - CodeSandbox. You need to enable JavaScript to run this app.
Read more >How to get React Router 4 to allow nested components inside ...
Here was my unsuccessful first-attempt using fragments: import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; ...
Read more >Fragments - React
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding...
Read more >Understanding React fragments - LogRocket Blog
Learn how to use React fragments to prevent rendering unnecessary nodes in the DOM and create an optimized code.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

I could see a case being made of not traversing the entire tree (which is clearly not going to work), but instead simply checking if a particular child is a Fragment. And, if it is, checking its immediate children. This helps with cases such as:
which seem like they will become pretty common as React 16 adoption grows. The alternative, using an array syntax with keys, is pretty ugly.
@timdorr, would you consider just looking inside of Fragments, or nah?
Actually, I specifically don’t want to flatten sub-children. It should only check
child.type === Fragmentand then returnchild.props.childrenfor processing in the loop. No recursion.