React Router – everything you need to know

In today’s article I will describe the basics of React Router, which is the most popular external library in React. It is responsible for our menu (navigation) in the application.


What is React Router?

Created for the first time in 2014, is a declarative routing library based on components on the client’s and server’s side. It adds and updates its users navigation history. If you’re a beginner in React, it may shock you, that it is not built into the library itself, but that's the basis of the premise for React, which focuses on providing the basics of the user interface for building applications and nothing more.


Route allows to map apps on different components. Let’s assume that we want to render a user’s profile component whenever user goes to the path /profile. It looks like that:

<Route
 path="/profile"
 element={<Profile />}
/>

Of course, you can render as many Routes as you want

<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/settings" element={<Settings />} />

It doesn’t matter if you have just one Route or more, place it inside Routes as follows:

import { Routes, Route } from "react-router-dom";

function App() { 
 return (
  <Routes>
   <Route path="/" element={<Home />} />
   <Route path="/about" element={<About />} />
   <Route path="/settings" element={<Settings />} />
   <Route path="*" element={<NotFound />} />
  <Routes>
 );
}

Links

Now that you know how to map your app’s location to specific React components using Routes and Route, the next step is to navigate between them. This is the purpose of the Link component, in which you pass it the destination address in the “to” attribute.

<nav>
 <Link to="/">Home</Link>
 <Link to="/about">O nas</Link>
 <Link to="/settings">Ustawienia</Link>
</nav>

If you need you to, you can also pass an object to the “it” attribute. This way you can add a query string through the “search” attribute or pass any data through the “state”.

<nav>
 <Link to="/">Home</Link>
 <Link to="/about">O nas</Link>
 <Link
  to={{
   pathname: "/settings"
   search: "?sort=date",
   state: { fromHome: true },

 >
  Ustawienia
 </Link>
</nav>


URL parameters

Allow you to declare a specific element in the URL address. For example forum. You will see, that the “/post/{postId}” pattern is the same. Instead defining Route for each post on forum, you can declare one Route with alternative symbol for each one of them. The way you tell that a certain part of the URL is a parameter is by using a colon in the path as shown in the example below.

<Route path="/post/:postId" element={<Post />} />

Now, if someone visits URL address that matches /post/:postId, the component is rendered. However, the question that arises is how to access the dynamic part of the URL, which in this case is the postld in the rendered component.


Invoking navigation

React Router offers a Navigate method for programmatic navigation. To access it, you will have to use useNavigate. From there, you can pass a new path for the user to be navigated to when it is called.

import { useNavigate } from "react-router-dom";

function Home() { 
 const navigate = useNavigate()

 return (
  <div>
   <Form afterSubmit={() => navigate('/dashboard')} />
  </div>
 );
}

Query strings

You must almost certainly have encountered query strings before. These are the “?” and “&” attached to a URL. They are a fundamental point of view when it comes to operating online, as they allow you to communicate the status through the URL.


They are used mostly in list and web filtering. For example, let’s take a list with data. It can be articles for blogs or advertisements for flat rentals. Now, we want to display primarily those we are interested in, so we either select the price range, area or type in the search engine specific words that the item contains in the list.


Since version 6, React Router has relied heavily on the URLSearchParams API interface to operate query strings. It is built into all browsers (except IE) and provides utility methods to operate on query strings. In order to do this, it comes with a custom useSearchParams hook that returns an array as in the example below.

import { useSearchParams } from "react-router-dom";

const Results = () => { 
 const [searchParams, setSearchParams] = useSearchParams();

 const q = searchParams.get('q')
 const src = searchParams.get('src')
 const f = searchParams.get('f')

 return (
  ...
 )
}

Non-existent 404 pages

I’m sure you’re wondering, what if a user invokes a Route that doesn’t exist, and how to add a single component for all such calls. All you need to do is to render the Route path as *, and React Router will make sure to render the given component that is displayed for non-existent pages, called error code 404.

<Routes>
 <Route path="*" element={<NotFound />}
 <Route path="/" element={<Home />} />
 <Route path="/about" element={<About />} />
 <Route path="/settings" element={<Settings />} />
</Routes>


Contrary to previous versions of React Router, the order of the Route sub-elements does not matter, meaning that the algorithm determines which one is the best to render. This makes rendering a component quite simple.


Conclusion

Routing is a very important concept and React Router is a huge library with lots of amazing features, which is the reason for its popularity. But most importantly, it allows us to redirect to another subpage without reloading the app, and it is very easy and useful to use.