Programmatically navigate to a different page using React Router?

  • Post category:React
  • Reading time:2 mins read

I want to navigate to a different URL in my React app when I click on a button or link. How to do it?

For using the navigation in the react application, first, you should install react-router dom using npm install react-router-dom

How to programmatically navigate using React Router?

In the React app, If I want to navigate programmatically, for example, by clicking a button, link, or menu to open a new page, I need to use the useNavigate hook. Let’s see a simple example of using useNavigate hook in our code.

// MyNavigationComponent.js
import React from 'react';
import { useNavigate } from 'react-router-dom';

function MyNavigationComponent() {
  const navigate = useNavigate();

  const programmaticallyNavigate = () => {
    navigate('/contact');
  };

  return (
    <div>
      <button onClick={programmaticallyNavigate}>Open contact us page</button>
    </div>
  );
}

export default MyNavigationComponent;

Code Explanation:

  • When a user clicks on the button “open contact us page” then programmaticallyNavigate function gets called and in that function, navigate will change the current route to the route mentioned inside navigate(‘/contact’).
  • So, this hook can be used to navigate programmatically to different routes in your react application.

Using useHistory Hook

If you are using react router v5, then you can use useHistory hook to navigate programmatically. useNavigate was introduced in v6. Both methods do the same thing but they are supported in different version as I mentioned.

Let’s see a simple example of using useHistory when clicking on a button.

// MyNavigationComponent.js
import React from 'react';
import { useHistory } from 'react-router-dom';

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

  const programmaticallyNavigate = () => {
     history.push('/contact');
  };

  return (
    <div>
      <button onClick={programmaticallyNavigate}>Open contact us page</button>
    </div>
  );
}

export default MyNavigationComponent;

Keywords – Navigate react, navigate react router, How to programmatically navigate using React Router?, How to navigate to different page using React Router?, how to navigate using react router? How to programmatically navigate using React Router, Programmatically navigate to a different page using React Router, Programmatically navigate using React Router

Share this