4

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?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • i think this topic is similar to this : https://stackoverflow.com/questions/69868956/how-to-redirect-in-react-router-v6 – Seif-Ch Mar 08 '22 at 14:39

1 Answers1

4

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>
                
micronyks
  • 54,797
  • 15
  • 112
  • 146