React-Router : The ultimate Web Navigation library đŸ”„

Yuvraj Pandey
6 min readMar 1, 2022
https://ichi.pro/

React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native.

In React, routers help create and navigate between the different URLs that make up your web application. They allow your user to navigate across the pages of your app while preserving user state and can provide unique URL names for these components to make them more shareable with the world. With routers, you can improve your app’s user experience by simplifying site navigation.

React-Router is one of the most popular routing frameworks for React. The library is designed to let you build a declarative routing system for your application. Declarative here means that you can declare exactly which of your components would a certain route which can be static or even dynamic in nature. With declarative routing, you can create routes that are human-readable, making it easier to manage your application architecture & navigation.

In this blog we would be touching on some of the core concepts related to React-Router :

  • Configuring Routes
  • Navigating with Link
  • Creating Links with active styling
  • Using Nested Routes for Layout
  • Navigating programmatically
  • Using URL params for data loading
  • Using URL Search params
  • “No Match” route

Installation

Most modern React projects manage their dependencies using a package manager like npm or Yarn. To add React Router to an existing project, the first thing you should do is install the necessary dependencies with the tool of your choice:

npm

$ npm install react-router-dom@6

Yarn

$ yarn add react-router-dom@6

Configuring Routes

Once the installation is complete we move on to configuring React-Router at the top level of the application. Simply import BrowserRouter which would then link our app to the Browser’s URL & render it around the entire App component as follows,

Now let us create a couple of new component files for AboutUs & ContactUs pages. We would then add these newly created files inside the Routes configuration which would let React Router know which files to render at what path.

Navigating with Link

Open the Home .js file now & import Link from React-Router to add some navigation business logic that would enable us to navigate across different pages within our app.

Now when we click on the About Us or Contact Us link we would be now able to navigate between all these pages seamlessly.

Creating Links with active styling

It’s very common, especially in navigation lists, to display the link as the active link the user is looking at. Let’s add this treatment to our demo by swapping out Link for NavLink.

We did three things there:

  1. We swapped out Link for NavLink.
  2. We changed the style from a simple object to a function that returns an object.
  3. We changed the color of our link by looking at the isActive value that NavLink passed to our styling function.

You can do the same thing with className on NavLink:

// normal string
<NavLink className="red" />

// function
<NavLink className={({ isActive }) => isActive ? "red" : "blue"} />

Using Nested Routes for Layout

You may have noticed when clicking the links that the layout inside Home.js disappears. Repeating shared layouts is a pain in the neck. We've learned that most UI is a series of nested layouts that almost always map to segments of the URL so this idea is baked right into React Router.

Let’s get some automatic, persistent layout handling by doing just two things:

  1. Nest the routes inside of the App route

First, let’s nest the routes. Right now the About Us and Contact Us routes are siblings to the home page, we want to make them the children of the home route.

  1. Render an Outlet

Add Outlet from React-Router at the bottom in Home.js & then if we click around, the parent route (Home.js) persists while the <Outlet> swaps between the two child routes (<AboutUs> and <ContactUs>)

Navigating programmatically

Most of the time the URL changes are in response to the user clicking a link. But sometimes you, the programmer, want to change the URL. So here we can use useNavigate hook from React-Router which allows us to navigate to any page programmatically from within our code,

“No Match” Route

When a user tries to navigate to any page which is not configured in the Route configuration then that route will load a blank empty page. In React-Router we can handle this scenario simply by adding <Route> with “*” path which has special meaning here & It will match only when no other routes do.

Using URL params for data loading

Let’s add a route for a specific product item. We just visited some URLs like "/products/11", let's make a new component in products as productItem.js to render at those URLs:

export default function ProductItem() {
return <h2>Product Item #???</h2>;
}

Ideally, we’d like to render the product item id instead of "???". Normally in React, you'd pass this as a prop: <ProductItem id="11" />, but you don't control that information because it comes from the URL.

Let’s define a route that will match these kinds of URLs and enable us to get the product item id from it.

Create a new <Route> inside of the "products" route like this:

Now let's create a Product.js & ProductItem.js file and a couple of things to note:

  • We just created a route that matches URLs like “/products/11” and “/products/123”. The :productItemId part of the path is a "URL param", meaning it can match any value as long as the pattern is the same.
  • The <Route> adds a second layer of route nesting when it matches: <App><Products><ProductItem /></Products></App>. Because the <Route> is nested the UI will be nested too.

Alright, now go click a link to a product item, note that the URL changes but the new product item component doesn’t show up yet. Do you know why?

That’s right! We need to add an outlet to the parent layout route.

Open up the Product Item component again and let’s read the :productItemId param from the URL. So in short.
..:invoiceId becomes params.invoiceId

Using URL Search params

Search params are like URL params but they sit in a different position in the URL. Instead of being in the normal URL segments separated by ‘/’, they are at the end after a ?. You've seen them across the web like "/login?success=1" or "/shoes?brand=nike&sort=asc&sortby=price".

React Router makes it easy to read and manipulate the search params with useSearchParams. It works a lot like aReact.useState() but stores and sets the state in the URL search params instead of in memory.

import { useSearchParams } from "react-router-dom";let [searchParams, setSearchParams] = useSearchParams();//Get search value from URL
const value = searchParams.get("productId")
//Set search value to URL
setSearchParams({ productId });

Important pointers

  • setSearchParams() are putting the ?productId=... search params in the URL and rerendering the router.
  • useSearchParams is now returning a URLSearchParams with "productId" as one of its values.

That’s it for this article hope you would have learned something useful from it. So If you have any thoughts or suggestions, feel free to leave a comment below. Don’t forget to share your love by clapping for this article as many times you feel like it.

You can follow me on Twitter, Github, LinkedIn, Facebook.

--

--

Yuvraj Pandey

Working towards striking an impact using technology for making this world a better place to live in âœ