Search code examples
reactjsreact-routerreact-router-dom

React JS React-router-dom Navigate not working


I try to redirect the user after login in my React App, but Navigate won't work and i don't know why...

Here is my code and thanks for your help

import React, { Component } from "react";
import {Route, Navigate} from 'react-router-dom';
import Bouton from "../components/Bouton";

class Dallan extends Component{
    logout = () =>{
        localStorage.removeItem('logged');
        return <Navigate to= '/login' />;
    }
    render(){
        return(
            <Bouton typeBtn = 'btn-danger' click={() => this.logout()}>Deconnexion</Bouton>
        )
    }
}

export default Dallan;

And in my App.js


function App() {
  let session = localStorage.getItem('logged');
  return (
    <BrowserRouter>
    <Routes>
    <Route path="/" element={session ? <Navigate to="/dallan" /> : <Login/>} />
       <Route path='/dallan' element={<Dallan/>}/>
    </Routes>
    </BrowserRouter>
 
  );
}

export default App;

Solution

  • If you are using react route dom v6 which I assume you are by the use of <Navigate /> then <Navigate /> is a component which would need to be rendered to work. You are just returning it to nothing so it obviously won't render. You want to use the useNavigate() hook instead. But you will want to use a function component to use the hook. Like so:

    import React, { Component } from "react";
    import {Route, useNavigate} from 'react-router-dom';
    import Bouton from "../components/Bouton";
    
    function Dallan() {
        const navigate = useNavigate();
        const  logout = () =>{
            localStorage.removeItem('logged');
            navigate('/login')
        }
    
        return(
            <Bouton typeBtn = 'btn-danger' click={() => logout()}>Deconnexion</Bouton>
        )
    }
    
    export default Dallan;