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.
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>