React Answers

How to programmatically navigate using React Router?

Spread the love

In React, we can programmatically navigate using React Router by using the useHistory hook provided by React Router.

For instance we write

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  const handleClick = () => {
    // navigate to a specific route

  return (
    <button onClick={handleClick}>Go to other route</button>

To use the useHistory hook to return the history object.

Then we call push to navigate to the /other-route route.

This is the most common method for programmatically navigating using React Router.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *