Programmatic Navigation in React Using React-Router

Learn via video courses
Topics Covered

Overview

You have probably learned how crucial it is to set up routing effectively while developing any modern web app. While browsing through many React Router tutorials you would have noticed that they usually concentrate mainly on how to utilize the Link component. The react-router-dom package can be used to control routing and redirect in React.

Introduction

The user event, state management, and render function are the three fundamental ideas that make up the React philosophy. One could argue that programmatic routing adheres to this philosophy.

The result of programmatic routing may be the same as no route modification or, in other cases, may necessitate a route change. We do not always need to employ a Link component, and it is not ideal to do so in these situations because the need would not always be brought about by following a link.

When a specific event occurs, or a user does an action, such as submitting a form that takes you to a different page, we want to redirect to a different route only then. This type of activity is referred to as programmatic navigation.

The earlier-mentioned ideology informs the architecture of React Router. As a result, by definition, programmatic navigation using React Router should adhere to those three fundamental ideas.

What is Programmatic Navigation?

In React Router, the programmatic navigation is basically the redirect in react, which occurs when an action such as clicking a button is taken. This is a simple technique that primarily guarantees that you will save time without any problem. Actions like registration or login are good choices for expediting the process and saving time. Using cutting-edge technology, it provides a practical choice for programmatic navigation. To achieve fast navigation the Redirect component and Navigation components are used.

Prerequisites

We will utilize the react-router-dom package in this tutorial; hence, we must install react-router-dom in our project. We can install react-router-dom by running any of the below-mentioned commands:

Alternatively,

Redirect and Navigate the Component

In earlier releases of the react-router-dom package, redirects could be performed very easily just by importing the Redirect component from the react-router-dom package. The Redirect component could be used by specifying the to prop, which would then specify the page you want to redirect to.

The Navigate component, which performs the same function as the Redirect component by accepting the to prop to enable you to redirect to the page you choose, was introduced with the introduction of React Router v6 and replaced the Redirect component.

Check to see if you have already specified the path. For example, if your goal is to redirect users to the \dummy route, you have to ensure that the route \dummy is set up in advance. In the following code, you should focus on the Route declarations' order.

Conditional Redirects

You will most likely need to use this when developing web applications. Routing is done through conditional redirect when specific conditions are met. This means that redirect in react happens only when certain conditions set by the developer are met. It can also be used to allow or block users from accessing particular components or forms etc.

For example, the developer does not want users to access the /dashboard route unless the user is logged in, so this can be done using the following code:

In the above code, a ternary operator is used, where props.loggedIn contains a boolean value, so if the boolean value is true it means that the user is logged in, then the user will be redirected to /dashboard, or else the user will be redirected to the /login route.

Another example where conditional redirect can be used is in the case of e-commerce sites where users will only be redirected to the /checkout route only if more than one item is added to the cart.

Replacing the Current URL

There might occur some instances where you want the current URL replaced rather than pushing or adding on to the history of the browser. To achieve the above effect, replace prop is used with the Navigate component.

When you are redirected to using this method, you will not be able to visit the previous page now.

Using history.push() Method

We can also utilize the history props that React Router offers when rendering a component by calling history.push().

Alternatively, we can say that history.push() functions when a component is rendered by React Router without using history as a prop in the Component to a route. If so, three props—location, match, and history—are made available to the component by the React Router.

The session history is tracked by the history prop, which also gives us several ways to change it.

The push method, which pushes a path as a route to the history stack that runs as Last In First Out(LIFO), is crucial. This forces the application to reroute to the most recent route added, sending the user on a predetermined route. Refer to the following example:

Using withRouter Method

Only a Component rendered using React Router will have access to props.history.push. This may not always be the case, though. We will have to render a component as a result. The React Router team developed the Higher Order Component (HOC) withRouter to make the history property accessible to the component. The characteristics are also exposed when a component is wrapped in this HOC.

Using useHistory Hook

This is used to navigate programmatically within a functional component. There is no need to utilize withRouter because the useHistory hook offers you access to the history instance which we can use to browse between pages(forward and backward also) whether or not the React Router has rendered the component.

Firstly, the useHistory() hook is imported, after which it is assigned to a variable and used, for example, in a button, to reroute users once a particular action is taken. After that, we can instruct React Router where to redirect the button by utilizing the onClick event to use the .push() method.

Programmatic Redirects with useNavigate()

In React Router v6, instead of the useHistory() hook, we now utilize a hook similar to the useHistory() hook, which is called useNavigate().

We import the hook and assign a variable to useNavigate() (similar to useHistory()), and then we use this variable for navigating the users to different routes.

Real-life Use Case: Private Routes Implementation

One of the real-life use cases of the routing methods mentioned above is Private routes implementation.

First, let us understand what Private routes are. Private routes are those routes(web pages) that are not accessible to users until they are authenticated or logged in. Profile pages, dashboards, etc. are an example of private routes because these are accessible to users only after the users are logged in.

PrivateRoute.js

In the code mentioned above, we created a component such that if the user is logged in, then the user will be redirected to the private page. The children prop is used to make the component scalable and reusable. children prop contains the component inside our Route component.

In the code above, we render the Login and Logout buttons conditionally based on whether the user is already logged in or not, which makes use of the useState hook.

Then we render the Welcome component, which is the public route, which means it does not require the user to be logged in and it is visible to everyone.

Now when we want to render our private pages, we pass the user prop and depending upon the login state of the user, the component will be rendered or not. The PrivateRoute component contains the route which needs to be rendered, so it is passed to the PrivateRoute component as a children prop, and it will be rendered by the PrivateRoute component.

Similarly, we will render the Dashboard component as it is a PrivateRoute.

The contact route is a public route, and it will remain unaffected by the login state of the user.

Conclusion

In this article, we have learned the following:

  • In React Router, the programmatic navigation is basically the redirect in react, which occurs when an action such as clicking a button is taken.
  • Actions like registration or login are good choices for expediting the process and saving time using programmatic navigation.
  • Redirect in react can be achieved using the Redirect component and Navigate component. The Redirect component was used in the previous versions.
  • In conditional redirect, redirect in react happens only when certain conditions set by the developer are met, which is achieved by using the ternary operator.
  • replace prop is used when you want to replace the current URL instead of pushing on into the browser history.
  • history.push() method utilizes the history prop to push the path as a route to the history stack.
  • In some instances, the history prop is not available to use in history.push(), so a higher order component(HOC) withRouter was developed that has access to the history property.
  • useHistory hook offers you access to the history instance which we can use to browse between pages whether or not the React Router has rendered the component.
  • In react-router v6 useNavigate hook was introduced to replace the useHistory hook to provide better compatibility.
  • Private routes are those routes that are only accessible to users only when they meet certain conditions set by the developer.