Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to <Redirect to="/login" /> using Navigate in react-router-dom v6? [duplicate]

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?

like image 437
Bobimaru Avatar asked Sep 11 '25 23:09

Bobimaru


1 Answers

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>
                
like image 74
Nikhil Shah Avatar answered Sep 14 '25 14:09

Nikhil Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!