skip to Main Content

I have a similar structure as the one below in my project, currently using react-router-dom v5.

Let’s call this <Routes /> component:

<Switch>
  <Redirect from="/" to="/some/path" />
  <Redirect from="/main" to="/some/path" />
  <Route path="/main" component={SomePage} />
</Switch>

And inside <SomePage />, I render something like this:

return (
<>
 <Tabs />
 <Switch>
    <Route path="/some/path" component={MyComponent} />
    <Route path="/some/other" component={OtherComponent} />
    <Route path="/some/last" component={LastComponent} />
 </Switch>
</>
)

Now I am updating react-router-dom to v6, so I changed what was written in their docs…

In <Routes /> component:

<RouterRoutes>
 <Route path="/" element={<Navigate to="/some/path" />} />
 <Route path="/main" element={<Navigate to="/some/path" />} />
 <Route path="/main" element={SomePage />} />
</RouterRoutes>

Did similar thing in <SomePage />, but now nothing is rendered and I don’t get what I need to change. I’ve looked on different threads around here on SO and Google and I still don’t get what is the recommended way to handle this whilst keeping project structure. I am trying to keep similar structure, as in <SomePage /> imports and creates its own routes and the main <Routes /> component is concerned only with the main routes.

2

Answers


  1. Hi You need to use Routes inside your component.
    <Routes>
     <Route path="/" element={<Navigate to="/some/path" />} />
     <Route path="/main" element={<Navigate to="/some/path" />} />
     <Route path="/main" element={"component name"}/>} />
    </Routes>
    
    Login or Signup to reply.
    • v5: <Switch> and <Redirect /> are used for conditional rendering and redirects.
    • v6: Use <Routes> and <Navigate /> for redirects and to wrap route definitions.

    In v5, you had:

    <Switch>
      <Redirect from="/" to="/some/path" />
      <Redirect from="/main" to="/some/path" />
      <Route path="/main" component={SomePage} />
    </Switch>
    

    In v6, you should update it to:

    import { Routes, Route, Navigate } from 'react-router-dom';
    
    <Routes>
      <Route path="/" element={<Navigate to="/some/path" />} />
      <Route path="/main" element={<Navigate to="/some/path" />} />
      <Route path="/main" element={<SomePage />} />
    </Routes>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search