Home > Software design >  Upgrading from React Router v5 to v6, what is the syntax for the following code?
Upgrading from React Router v5 to v6, what is the syntax for the following code?

Time:01-03

I am making a search engine and want to route an array path to render Results component. The code for React Router v5 is this:

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

What will be the v6 compatible syntax for this? I have tried the following, but it's not working:

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

I have imported Routes and Route import { Routes, Route} from "react-router-dom"; of course.

CodePudding user response:

I don't think it supports arrays anymore and the regex that could be used is not supported anymore (see https://reactrouter.com/docs/en/v6/upgrading/v5). The type definitions also says path: string. So you would need

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

CodePudding user response:

You can do as @bas answered or for a more easy approach and less typing, just do this.

{["/r1", "/r2", "/r3"].map((path, i) => (
    <Route path={path} key={i} element={<div>Same route</div>} />
))}

Here is an example:

https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/App.js:2717-2846

  • Related