There two common use-cases for redirecting a user within React. One is upon successful login, the other is if you want a catch-all route to take people to a 404.
To redirect the user upon login you could try pushing to the history object but there is a more “React” way of doing it by using the <Redirect /> component from react-router-dom. The way it works is that you conditionally place the component within your render function. For example:
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; class Login extends Component { constructor(props) { super(props); this.state = { redirect: false, }; } doRedirect = (e) => { this.setState({redirect: true}); } render() { const { redirect } = this.state; if (redirect){ return <Redirect to='/dashboard' /> } return ( <div> <h1>Hello</h1> <button onclick="this.doRedirect">redirect</button> </div> ); } } export default Login;
As you can see the Redirect component is conditionally rendered when the redirect state prop is updated.
Assuming you have setup react-router such that the “/dashboard” path exists then clicking the button will update “redirect” to “true”, the Redirect component is rendered into the page triggering the redirect and the “/dashboard” is displayed.
For a catch-all page you can also use the <Redirect /> component by rendering it directly from the catch-all route:
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'; function Page() { return <h2>Hello</h2>; } function AppRouter() { return ( <Router> <div className="App"> <Route path="/" exact component={page} /> <Route path="/*" render={() => <Redirect to="/" />} /> </div> </Router> ); } export default AppRouter;