Home > Enterprise >  Passing array of paths to "Route" throws error
Passing array of paths to "Route" throws error

Time:12-19

Whenever I am giving array of paths to Route it gives following error :

meta.relativePath.startsWith is not a function

Code snippet:

 <Route
          path={["/search", "/images", "/news", "/videos"]}
          element={<Results />}
 ></Route>

The tutorial which I was following was using older version of React router and thus they were also using Switch and that's why it was working fine in the tutorial.

Since in v6 Switch is no longer available and I also tried to go through docs regarding how to pass array of path, but didn't find anything which can solve the error

CodePudding user response:

react-router v6 doesn't support passing an array of path in Route.

If you want to keep the same behavior, you need to separate it into multiple Route like this

<Route
  path="/search"
  element={<Results />}
/>
<Route
  path="/images"
  element={<Results />}
/>
<Route
  path="/news"
  element={<Results />}
/>

<Route
  path="/videos"
  element={<Results />}
/>

or a shorter way is to use .map

{
  ["/search", "/images", "/news", "/videos"].map((p) => (
    <Route key={p} path={p} element={<Results />} />
  ));
}

  • Related