navigate using React Router

React Router provides a useHistory hook and useNavigate hook (starting from version 6) that allows you to programmatically navigate within your React components.

Here’s an example using both approaches:

Using useHistory (React Router v5):

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

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

  const handleButtonClick = () => {
    // Programmatically navigate to a different route
    history.push('/another-route');
  };

  return (
    <div>
      <h1>My Component</h1>
      <button onClick={handleButtonClick}>Go to Another Route</button>
    </div>
  );
};

export default MyComponent;

Using useNavigate (React Router v6):

import React from 'react';
import { useNavigate } from 'react-router-dom';

const MyComponent = () => {
  const navigate = useNavigate();

  const handleButtonClick = () => {
    // Programmatically navigate to a different route
    navigate('/another-route');
  };

  return (
    <div>
      <h1>My Component</h1>
      <button onClick={handleButtonClick}>Go to Another Route</button>
    </div>
  );
};

export default MyComponent;

useHistory or useNavigate hooks are imported from ‘react-router-dom‘.

The hook is called to get the necessary function (history or navigate) for programmatically navigating.

Inside an event handler (e.g., a button click), you call the navigation function (history.push or navigate) with the desired route as an argument.

If you are using React Router version 6 or later, it’s recommended to use useNavigate as it is designed to work with the new features and improvements introduced in those versions.

About the author

Full-stack web developer with great knowledge of SEO & Digital Marketing. 7+ years of experience in Web Development.

Leave a Reply