react-router to implement dynamic navigation in React
Tags: react, webdev
Published: 2024-03-07 15:15:24

Navigation is essential for any web application. As you know, React allows us to build Single Page Applications. These types of apps are rendered in the browser at once. URL only determines which parts of the application is showed to the user.

React-router is the most popular package for handling routing in React. It is a great tool that gives you plenty of opportunities for navigation between pages and components. Let’s explore different avenues for implementing navigation features in React. 

## Navigation using <Link> component

React-router comes with many custom components to help you implement essential navigation features in React.

As you know, Single Page Apps are all rendered on the same page, so there’s no need to refresh the page. <Link> is perhaps the most useful custom component for navigation in React. It works similar to `<a>` tag in HTML, except <Link> does not reload the page. The website automatically navigates to a different URL. Then React renders appropriate components for that URL.

Similar to normal `<a>` tag, you can set to attribute on <Link> component. The to attribute is set to a string that specifies relative path to navigate to. For example, if the current page is homepage.com/dashboard/, and the to attribute is set to ‘/somepage/, then clicking the url will take user to homepage.com/dashboard/somepage.

You can also set event handlers on <Link> like you do on `<a>` tag.
 
## Go back in React

Going back to the previous page is one of the essential features of navigation in React. Browsers usually store your browsing history in history object. This object is available on window interface. You can work with this object to navigate to previous page in React.

Latest version of React Router provides useNavigate hook, which is essential to implement go back feature. useNavigate returns a function you can use to navigate forward, backward, or even several steps backward.

You only need to specify argument to the navigation function to specify how many steps you want to go back or forward. If you want to go back to previous page, pass it -1. It will take you one step back.

Note that you don’t pass argument to the useNavigate hook, but the function it returns. Also don’t forget that you can only use react-router features if the application is wrapped with parent <BrowserRouter> component.

You can also implement go back features in previous features of react-router. In versions 4 and 5 you need to use the useHistory() hook to navigate backwards in React. The hook returns instance of history object. Its interface includes the goBack() method, which takes user to the previous page.

Newest react-router 6 comes with many other upgraded features. Most interesting to me was setting react router optional path param, more about that here:

https://simplefrontend.com/optional-parameter-in-react-router/. 

## Redirect in React

Often times you need to redirect users to React. For example, when someone logs in, redirect them to a dashboard. You can do that number of ways in React.

Let’s start with how to do redirects in the most recent version of react router 6.
 
Once again, you are going to need the useNavigate() hook to get a navigation function. Once you have that, simply call the function and pass it a string argument. The app will redirect users to that relative path. This way, you can programmatically redirect users to a different URL. You can insert the call to the navigation function in event handlers, or even lifecycle methods.

Another way is to render a custom <Navigate> component, which is also available with react-router 6. If invoked and successfully rendered, this custom component will redirect users to the path in the to prop.

Great thing about invoking a Navigate component is that you can use it in functional as well as class components. Whereas the useNavigate hook is reserved only for functional components.
You can even use curly braces to conditionally render a Navigate custom component in the JSX. Remember that React allows you to embed dynamic expressions inside the structure of your app. That’s what makes it vastly better than other front-end frameworks out there. You can use similar techniques to conditionally call the navigation function.

Typically you’d use a state or props value to set a condition. If the state changes, then the redirect happens. Ternary operators also allow you to specify two options: redirect to a certain path if the condition is true, and to another if the condition is false.

## Redirect on button click

Programmatic navigation is necessary to do a redirect in response to events in React. Click event is no exception.

Once again, you need a useNavigate() hook to create a navigation function. Then call it inside an onClick event handler, which will run every time user clicks the button. And of course specify the relative path you want to redirect the user. Once set, clicking the button will redirect users to that URL. [This is how you redirect](https://simplefrontend.com/redirect-to-external-url-in-react/) to external URL in React on click of a button. 

You can also set an onClick event handler on custom Link component. 

## Redirect on form submit

Sometimes you also need to redirect users to a different URL after the form is submitted. To do that, you need to set onSubmit handler on the <form> element itself. In the event handler, you are going to call the navigation function to take user to a specified URL.

Needless to say, the form also needs to have a submit button. That is, button where the type attribute is set to ‘submit’.