Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Dom V6 pass array to path

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.

like image 825
Josh Liu Avatar asked Jan 24 '26 01:01

Josh Liu


2 Answers

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.

Key prop

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.

Playground

https://stackblitz.com/edit/github-otdpok?file=src/App.tsx

like image 147
pgarciacamou Avatar answered Jan 26 '26 18:01

pgarciacamou


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>
like image 22
A_A Avatar answered Jan 26 '26 17:01

A_A