How do you programmatically navigate using React Router v4?
There are three different ways to achieve programmatic routing/navigation within components.
-
Using the
withRouter()
higher-order function:The
withRouter()
higher-order function will inject the history object as a prop of the component. This object providespush()
andreplace()
methods to avoid the usage of context.import { withRouter } from 'react-router-dom'; // this also works with 'react-router-native'const Button = withRouter(({ history }) => (<buttontype="button"onClick={() => {history.push('/new-location');}}>{'Click Me!'}</button>)); -
Using
<Route>
component and render props pattern:The
<Route>
component passes the same props aswithRouter()
, so you will be able to access the history methods through the history prop.import { Route } from 'react-router-dom';const Button = () => (<Routerender={({ history }) => (<buttontype="button"onClick={() => {history.push('/new-location');}}>{'Click Me!'}</button>)}/>); -
Using context:
This option is not recommended and treated as unstable API.
const Button = (props, context) => (<buttontype="button"onClick={() => {context.history.push('/new-location');}}>{'Click Me!'}</button>);Button.contextTypes = {history: React.PropTypes.shape({push: React.PropTypes.func.isRequired,}),};
September 30, 2022
814
Read more
What is React?
November 06, 2022
ReactJSHow to programmatically trigger click event in React?
November 06, 2022
ReactJS