JN Jony Hossain
JN Jony Hossain

Reputation: 37

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

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

Upvotes: 4

Views: 10509

Answers (2)

Drew Reese
Drew Reese

Reputation: 203417

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>

Upvotes: 4

Rakesh
Rakesh

Reputation: 167

Try this

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

Upvotes: 2

Related Questions