Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 270
JN Jony Hossain Avatar asked Nov 02 '25 17:11

JN Jony Hossain


1 Answers

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>
like image 117
Drew Reese Avatar answered Nov 05 '25 16:11

Drew Reese