Skandh Gupta

Skandh Gupta started this conversation 4 months ago.

20

1

react

How to programmatically navigate using React Router?

How can you navigate programmatically within a React application using the React Router library?

codecool

Posted 4 months ago

Navigating programmatically within a React application using the React Router library is quite handy when you need to redirect users based on actions or conditions in your app. Here's a step-by-step guide on how to achieve this:

  1. Using the useHistory Hook: The useHistory hook from react-router-dom is commonly used for navigation. It provides access to the history instance, which can be used to navigate.

  2. Using the useNavigate Hook: In the newer versions of React Router, useNavigate replaces useHistory.

  3. Using the withRouter Higher-Order Component: If you're working with class components, you can use the with Router HOC to gain access to the history object.

  4. Using the Navigate Component: For conditional navigation in functional components, you can use the Navigate component from react-router-dom.