Navigate from one page to another page in ReactJS

Today we will teach you how to navigate from one page to another page in ReactJS. There are multiple ways to redirecting from one component to another component in ReactJS. In this article, you will find all possible ways to manage redirection.

Before you start looking into it, I will recommend you to check the Routing in ReactJS.

Way to navigate from one page to another page

  1. Link
  2. NavLink
  3. Redirect Component
  4. history.push
  5. history.replace

Link is used to manage the navigation and it worked as an anchor tag. Check below code for the demonstration.

NavLink behaves the same as Link but in addition, it comes with a new attribute called “activeClassName” which helps us to add the class to the anchor tag when page url will match.

In the above example, when url will match the /about then active class will be added to the link.

React router is a very huge library to implement routing in React. Did you know about the React Router version 6? Refer to the link below for more information.

What’s new in React Router version 6

3. Redirect Component

Rendering a <Redirect to="/path/to/redirect" /> component is used to manage the redirection. When you manage the redirection through the <Redirect> component then it will override the current location in the history stack.

4. history.push

If you want programmatically navigation from one page to another then you should use history.push method. In other words, we can say if you want to manage the redirection on button click then you can use it. This function will push a new entry in the history stack.

You can also write the code below.

You can retrieve the state variable using the code below.

5. history.replace

history.replace function will replace the current location in the history stack and manage the redirection same as the history.push.

The first parameter is the path name as a string without object, and the second parameter is the state as a object.

I would also like to share the link of the Nested Routes in React JS.

That’s it for today.
Thank you for reading. Happy Coding!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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