'How to redirect to a new page from a function in React?
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?
Solution 1:[1]
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);
Solution 2:[2]
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.
Solution 3:[3]
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>
)
}
}
Solution 4:[4]
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")
Solution 5:[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.
Solution 6:[6]
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
Solution 7:[7]
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>
)
}
Solution 8:[8]
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
Solution 9:[9]
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
Solution 10:[10]
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/"
}
Solution 11:[11]
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;
Solution 12:[12]
logout(){
localStorage.clear();
this.setState({redirect: true})
}
//inside Render
render(){
const {redirect} = this.state;
if(redirect){
return <Redirect push to="/login"/>
}
}
Solution 13:[13]
You need to import Redirect from react-router-dom, like this:
import { Redirect } from 'react-router-dom';
Solution 14:[14]
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} ..>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
