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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With