Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

This tutorial will help you to use react-router in your react.js functional component, basically, we pass history from props and use it in the functional components.

But we have a better way to use history screen navigation in the function component.

In this tutorial example based on react-router-dom package.

React router dom provides useHistory() method to use history without passing from props.

let do example of useHistory() in react functional component.

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

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

  const redirect = () => {
    history.push('/login');
  }

  return (
    <div>
      <h1>Hi there!</h1>
      <button onClick={redirect}>Log in</button>
    </div>
  );
};

After importing the useHistory() method and store in veriable, we have the same syntax to navigate the diferant screens like below.

history.push('/login');

If in case useHistory() method not working for you try useNavigate() method.

Thanks for reading…