I want to render same page by multiple routes in react-router-dom v6 like how it was in v5. However, I couldn't find a efficient way to do it.
Example in v5 I can do this:
<BrowserRouter>
<Switch>
<Route path={["/dashboard", "/home"]} render={<Home />} />
<Route path="/other" render={<OtherPage/>} />
<Route path={["/", "/404"]} render={<NotFound />} />
</Switch>
</BrowserRouter>
But in v6, it is said that the path needs to be a string.
The only way I found that can achieve this is to separate them as follow:
<BrowserRouter>
<Routes>
<Route path="/dashboard" element={<Home />} />
<Route path="/home" element={<Home />} />
</Routes>
</BrowserRouter>
Which means I have to write <Home /> multiple times.
I want to keep my code as CLEAN as possible.
I checked the official documentation, but didn't mention about this part. And I did research, but couldn't find a solution.
There is no need for custom solutions. The cleanest solution is to loop internally:
<Routes>
{["/dashboard", "/home"].map(path => (
<Route
key="Home" // optional: avoid full re-renders on route changes
path={path}
element={<Home />}
/>
))}
</Routes>
For your use case with only two routes, I personally think having separate routes is more readable. But for my use case; where I have 6+ routes pointing to the same component, it doesn't make sense any longer.
The fixed key is a "hack" that's only needed for specific cases where your users have a way to switch between the URLs internally and/or if the component is heavy. Using the same key for all routes in the Array tells React that the component didn't unmount when React Router switches routes and that only the props changed, this way React doesn't re-render the entire branch. It works because React Router v6 never renders two routes at any point in time.
https://stackblitz.com/edit/github-otdpok?file=src/App.tsx
I created this helper function and it works in React Router v6:
const renderMultiRoutes = ({ element: Element, paths, ...rest }: MultiRoutes) =>
paths.map((path) => <Route key={path} path={path} {...rest} element={Element} />);
Then I can do the following:
<Routes>
{renderMultiRoutes({
paths: ['/', '/dashboard'],
element: <Feature />,
})}
</Routes>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With