Home > database >  how can i upgrade it to react-router-dom v6
how can i upgrade it to react-router-dom v6

Time:06-10

I have the following v5 code:

</Switch>
  ...
  <Route path="/home">
    <Header />
    <Home />
  </Route>
</Switch>

v5 code

Hello how can I upgrade it to v6 ?

I tried this code but it doesn't work.

<Route exact path="/home" element={((<Home />), (<Header />))}>

CodePudding user response:

Issue

element={((<Home />), (<Header />))}> is actually a Comma Operator expression, which when evaluated returns the value of the last operand, <Header /> in your case.

Solution

To convert the react-router-dom@5 code

</Switch>
  ...
  <Route path="/home">
    <Header />
    <Home />
  </Route>
</Switch>

to react-router-dom@6 API/syntax, replace the Switch component with the Routes component and move the routed content onto the Route component's element prop:

<Routes>
  ...
  <Route
    path="/home"
    element={(
      <>
        <Header />
        <Home />
      </>
    )}
  />
</Routes>

If rendering the header component with several routes it is common to create layout routes that render common UI and an Outlet for nested routes to render their element into.

Example:

import { Outlet } from 'react-router-dom';

const HeaderLayout = () => (
  <>
    <Header />
    <Outlet />
  </>
);

...

<Routes>
  ... routes w/o Header
  <Route element={<HeaderLayout />}>
    <Route path="/home" element={<Home />} />
    ... other routes to render with Header
  </Route>
</Routes>

CodePudding user response:

To upgrade your package to v6 you need to first uninstall react-router-dom package & then try to install using the below command-

npm install react-router-dom@6

  • Related