How to redirect to login page on click of logout in react

10,698

Use WithRouter to access history object

 import React,{Component} from 'react';
 import { withRouter } from 'react-router'
import {BrowserRouter,Link,Route} from 'react-router-dom';
import Contact from './contact';

class Home extends Component {
    constructor(props) {
        super(props)
    }

    logoutHandler =(e) => {
        this.props.history.push('/login')
    }

    render() {
        return(
            <BrowserRouter>
                <div>
                    <header>
                        <Link to='/contact'>Contact</Link>
                    </header>
                    <div>
                        <Route path='/contact' Component={Contact}></Route>
                    </div>
                    <a href="#" onClick={e=>this.logoutHandler(e)}>Logout</a>
                </div>
            </BrowserRouter>
        )
    }
}
export default withRouter(Home);
Share:
10,698

Related videos on Youtube

denzil
Author by

denzil

Updated on June 04, 2022

Comments

  • denzil
    denzil almost 2 years

    Sorry for my bad English, English is not my first language.

    Hi, I am new to react JS, in the below code everything is working fine but when I click logout handler it shows

    " × TypeError: Cannot read property 'replace' of undefined "

    Can you please let me know how can i redirect to login page on click of logout handler,

    I tried all possibilities like:

    this.props.history.push('somepath') this.context.history.push('somepath') but nothing worked for me I researched lot but didn't found actual answer.

     import React,{Component} from 'react';
    import {BrowserRouter,Link,Route} from 'react-router-dom';
    import Contact from './contact';
    
    class Home extends Component {
        constructor(props) {
            super(props)
        }
    
        logoutHandler =(e) => {
            this.props.history.replace('/login')
        }
    
        render() {
            return(
                <BrowserRouter>
                    <div>
                        <header>
                            <Link to='/contact'>Contact</Link>
                        </header>
                        <div>
                            <Route path='/contact' Component={Contact}></Route>
                        </div>
                        <a href="#" onClick={e=>this.logoutHandler(e)}>Logout</a>
                    </div>
                </BrowserRouter>
            )
        }
    }
    export default Home;`