Home > Blockchain >  How to Using React Routing Navigate instead Redirect in react-router-dom v6
How to Using React Routing Navigate instead Redirect in react-router-dom v6

Time:12-31

I saw this in a tutorial

In the Navigation Component

<li><NavLink to='/'>Home</NavLink></li>

In another Component

import Navigation from './Headers/Navigation' 
import Home from './Body/Home'
<Navigation />   
<Switch>
<Route path='/' exact component={Home} />
<Redirect from ='/' to='/Home'/>
<Switch />

I tried to learned the latest update and tried the above code by :

<Routes>
<Route path='/' element={<Navigate to='/Home' />} />
<Routes>

But what I really want doesn't work

CodePudding user response:

Try this

...
<Route path='*' element={<Navigate to='/Home' />} />
...

CodePudding user response:

You still need to render the route you are redirecting to. Note that for the redirect to work correctly in the Switch component the Home component needs to render on a path other than "/" otherwise Home will match and render and the Redirect will never be reached.

v5

<Switch>
  <Route path='/home' component={Home} />
  <Redirect from ='/' to='/home'/>
<Switch />

v6

<Routes>
  <Route path='/home' element={<Home />} />
  <Route path='/' element={<Navigate to='/home' replace />} />
<Routes>
  • Related