Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading