31

Right now I have this function in react and I am using it to go back to login and also to check reset the localStorage value for which I am using the function and not since using that I cannot reset local storage value. The function is below:-

logout(){
    localStorage.clear();
    console.log("cliasdk");
    return(
        <Redirect to="/login"/>
    )
  }

This gets executed on clicking a div but I am not able to go to the /login page.How to do it?

hearty
  • 691
  • 5
  • 10
  • 15

14 Answers14

19

If you use the react-router-dom package you can wrap your component with a router and then you have the ability to redirect the user programmatically, like so this.props.history.push('/login').

Eg:

import {withRouter} from 'react-router-dom';

class Component extends React.component {

    constructor(props){

    }

    componentDidMount(){
        this.props.history.push('/login');
    }

}

export default withRouter(Component);

See: https://www.npmjs.com/package/react-router-dom.

Adam
  • 1,724
  • 13
  • 16
9

With all previous answers, I'll describe here this use case:

on `/login` page, I would like to go to `/` when login is OK:

Add imports:

import { Redirect } from 'react-router-dom';

Add in your component default state a redirect to false:

state = {
  redirect: false,
}

Add to your business logic (ex. onLoginOk()) a change of the redirect state

this.setState({ redirect: true })

Add somewhere in your render root element:

 { this.state.redirect ? (<Redirect push to="/"/>) : null }

That's it.

boly38
  • 1,806
  • 24
  • 29
  • 1
    How about to function-based? You're not answering the question. The question is about function-based, not class-based, lol? – Edison Pebojot Mar 21 '21 at 03:14
  • @EdisonPebojot you can also put your own business logic using my sample : in addition to state update in your "onLoginOk" function, you could add other directives. On another way, you could avoid using intermediate state by calling directly `window.location.href= '/';` – boly38 Mar 21 '21 at 12:18
7

you can use this example for redirect after rendering a function

import React from 'react';
import { Redirect } from 'react-router-dom';

class MyComponent extends React.Component {
  state = {
    redirect: false
  }
  setRedirect = () => {
    this.setState({
      redirect: true
    })
  }
  renderRedirect = () => {
    if (this.state.redirect) {
      return <Redirect to='/target' />
    }
  }
  render () {
    return (
       <div>
        {this.renderRedirect()}
        <button onClick={this.setRedirect}>Redirect</button>
       </div>
    )
  }
}
fatemeh kazemi
  • 516
  • 6
  • 10
6

This is the simplest if you don't want to deal with react-router-dom.
Here's an example written in react functional components

const Page = () => {
   const redirect = () => {
      window.location.href = '/anotherPagePath'
   }
   return (
      <button onClick={redirect}>go to another page</button>
   )
}
Daryll
  • 503
  • 1
  • 9
  • 15
5

You can use history variable in props or if haven't history in props, you can use withRouter HOC (https://reacttraining.com/react-router/web/api/withRouter)

history.push("/login") 

or

history.replace("/login")
san
  • 1,515
  • 11
  • 18
5
import React from "react"
import { useHistory } from "react-router-dom";

export const Component = ( props ) => {
  const history = useHistory()
  const handler = () => {
    //Redirect to another route
    history.push("/route-link") 
  }
}

Maybe that's what you are looking for.

Rene Arteaga
  • 334
  • 3
  • 6
4

If you are trying to logout in a React application (that uses the URL pattern /#/page) through a function that clean the local storage / redirect, try to use go:

import { createHashHistory } from "history";

const history = createHashHistory();

history.go("/login");

The go loads a specific URL from the history list, this can be used to go back in the history, but also to go foward, in this case the 'foward' will use /login and the absolute path to redirect.

Update

On React Router 6 you can use useNavigate to navigate programmatically

3

In React router 6, redirection looks like this:

const navigate = useNavigate();
const goToLoginPage = () => navigate('/login');

All the code can be seen here: https://github.com/anmk/redirect/blob/redirect/src/App.js

You can also write a component to do this: https://github.com/anmk/redirect/tree/redirect_to_component

Andrzej
  • 101
  • 1
  • 1
2

You can change route programmatically, with history like this:

export default class Logout extends Component {
  logout = () => {
    this.props.history.push("login");
  };

  render() {
    return (
      <div>
        <h1>Logout</h1>
        <button onClick={this.logout}>Logout</button>
      </div>
    );
  }
}

If you need localStorage.clear();, just put it in logout function. You can see full (working) code example here: https://codesandbox.io/s/py8w777kxj

Vikky
  • 750
  • 8
  • 16
2

For future reference, if you're not interested in using React Router you could try the same as I use right now which uses the browser's location (URL):

logout(){
    // stuff...
    location.href = "/login/"
  }
Kostas Mouratidis
  • 1,145
  • 2
  • 17
  • 30
2

Try this


import React from "react";
const createHistory = require("history").createBrowserHistory;

class Logout extends React.Component {
    constructor(props) {
        super(props);
        let history = createHistory();
        history.push("/login");
        let pathUrl = window.location.href;
        window.location.href = pathUrl;   

    }

    render() {

        return (
            <div>
            </div>
        );
    }
}

export default Logout;
abnaceur
  • 252
  • 1
  • 2
1
logout(){
    localStorage.clear();
    this.setState({redirect: true})
  }

//inside Render
render(){
    const {redirect} = this.state;
   if(redirect){
    return <Redirect push to="/login"/> 
}
}
Deee
  • 331
  • 2
  • 9
  • 27
0

You need to import Redirect from react-router-dom, like this:

import { Redirect } from 'react-router-dom';
Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
  • This has nothing to do with the question, nothing implies that the OP did not import already. I know becaus I have the same issue and not the importing. – MattSom Nov 28 '20 at 19:24
0

This is how I solved the problem.

import {useDispatch} from "react-redux";
import useRouter from 'hooks/useRouter'

const {push} = useRouter();
const dispatch = useDispatch();

const logout = () => {
    localStorage.clear();
    push("/login");        
    dispatch({
        type: LOGOUT_STARTED,
        payload: false,
    });
};

<... onClick={logout} ..>