Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to a new page from a function in React?

Tags:

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?

like image 612
hearty Avatar asked Jun 11 '18 08:06

hearty


People also ask

How do you auto redirect to another page in react?

import { Redirect } from "react-router-dom"; The easiest way to use this method is by maintaining a redirect property inside the state of the component. Whenever you want to redirect to another path, you can simply change the state to re-render the component, thus rendering the <Redirect> component.


2 Answers

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.

like image 187
Adam Avatar answered Oct 12 '22 16:10

Adam


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.

like image 26
boly38 Avatar answered Oct 12 '22 15:10

boly38