React logout redirect to login

React logout redirect to login | logout component react Example

In the below examples, I Implementing client-side logout with React Router and there are two things I had to do to make this work:
1.      Clear the token in localStorage
2.      Push the url for the homepage onto the history prop

Example 1,
import React, { Component } from 'react'
import { baseUrl } from '../assets/js/helpers';

export default class Logout extends Component {

  logout = () => {
    window.localStorage.clear();
    window.location.href = baseUrl + "login";
  }
  
  render() {
    return (
      <button onClick={this.logout}>Logout</button>
    )
  }
}

Example 2,
import React from 'react'
import { baseUrl } from '../assets/js/helpers';

export default () => {
  const logout = () => {
    window.localStorage.clear();
    window.location.href = baseUrl + "login";
  }

  return (
    <button onClick={logout}>Logout</button>
  )
}

Example 3,
import { ComponentPropTypes } from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import * as authActionCreators from '../actions/auth'

class LogoutPage extends Component {

  componentWillMount() {
    this.props.dispatch(authActionCreators.logout())
    this.props.router.replace('/')
  }

  render() {
    return null
  }
}

LogoutPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
  router: PropTypes.object.isRequired
}

export default withRouter(connect()(LogoutPage))


You should check out the docs.

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^