I had the following piece of code while using react-router-dom v5 that redirected me to login if the user wasn't authenticated and to the rest of the application if he was:
!isAuthenticated ? (
<>
<Route path="/login" exact component={Login} />
<Redirect to="/login" />
</>
) : (
<div className="d-flex flex-column min-vh-100">
<main>
<Container className="mt-4">
<Switch>
<Route path="/" exact component={Home} />
<Route path="/collections" component={Collections} />
<Redirect to="/" />
</Switch>
</Container>
</main>
</div>
)}
After upgrading to react-router-dom v6, I had to do some refactoring which ended up looking like this:
!isAuthenticated ? (
<>
<Routes>
<Route path="/login" element={<Login />} />
</Routes>
<Navigate replace to="/login" />
</>
) : (
<div className="d-flex flex-column min-vh-100">
<main>
<Container className="mt-4">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/collections" element={<Collections />} />
</Routes>
<Navigate to="/" />
</Container>
</main>
</div>
)}
From what I understand, <Navigate replace to="/login" /> is the react-router-dom v6 equivalent of <Redirect to="/login" />, but right now my code puts me in an infinite loop. Why is this happening?
You can keep <Navigate> inside <Routes> as shown below,
<Routes>
<Route path="/" element={<Navigate replace to="/login" />} /> // OR path='/login'
<Route path='/login' element={<Login/>}
</Routes>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With