Home >Web Front-end >JS Tutorial >How to Programmatically Navigate in React Router v4, v5, and v6?
Navigating Programmatically with React Router
In React Router, the Link element enables native navigation using hyperlinks. However, for programmatic navigation beyond links, you can leverage the following methods.
React Router v6.6.1 and Above: useNavigate Hook
Utilize the useNavigate hook as follows:
import { useNavigate } from "react-router-dom"; function HomeButton() { const navigate = useNavigate(); function handleClick() { navigate("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); }
React Router v5.1.0 and Above: useHistory Hook
For functional components, consider the useHistory hook:
import { useHistory } from "react-router-dom"; function HomeButton() { const history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); }
React Router v4: Multiple Approaches
Inject the history object as a component prop:
import { withRouter } from "react-router-dom"; const Button = withRouter(({ history }) => ( <button type="button" onClick={() => { history.push("/new-location") }} > Click Me! </button> ));
Render a pathless route that always matches the current location, providing the history methods via the history prop:
import { Route } from "react-router-dom"; const Button = () => ( <Route render={({ history }) => ( <button type="button" onClick={() => { history.push("/new-location") }} > Click Me! </button> )} /> );
Access history via the React Context API:
const Button = (props, context) => ( <button type="button" onClick={() => { context.history === history.push === history.push; context.history.push('/new-location') }} > Click Me! </button> ); Button.contextTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired }) };
For simplicity, we recommend using the withRouter higher-order component or rendering a pathless route with composition.
The above is the detailed content of How to Programmatically Navigate in React Router v4, v5, and v6?. For more information, please follow other related articles on the PHP Chinese website!