React-Router v6+ Answer
You can use the new useNavigate
hook. useNavigate
hook returns a function that can be used for programmatic navigation. Example from the react-router documentation
import { useNavigate } from "react-router-dom"; function SignupForm() { let navigate = useNavigate(); async function handleSubmit(event) { event.preventDefault(); await submitForm(event.target); navigate("../success", { replace: true }); } return <form onSubmit={handleSubmit}>{/* ... */}</form>; }
React-Router 5.1.0+ Answer (using hooks and React >16.8)
You can use the useHistory hook on Functional Components and Programmatically navigate:
import { useHistory } from "react-router-dom"; function HomeButton() { let history = useHistory(); // use history.push('/some/path') here };
React-Router 4.0.0+ Answer
In 4.0 and above, use the history as a prop of your component.
class Example extends React.Component { // use `this.props.history.push('/some/path')` here };
NOTE: this.props.history does not exist in the case your component was not rendered by . You should use to have this.props.history in YourComponent
React-Router 3.0.0+ Answer
In 3.0 and above, use the router as a prop of your component.
class Example extends React.Component { // use `this.props.router.push('/some/path')` here };
React-Router 2.4.0+ Answer
In 2.4 and above, use a higher order component to get the router as a prop of your component.
import { withRouter } from 'react-router'; class Example extends React.Component { // use `this.props.router.push('/some/path')` here }; // Export the decorated class var DecoratedExample = withRouter(Example); // PropTypes Example.propTypes = { router: React.PropTypes.shape({ push: React.PropTypes.func.isRequired }).isRequired };