How to get started with routing in React apps with React Router
Marcin Kwiatkowski /
React is a popular library for developing single-page applications (SPAs) that can be rendered on the client-side. In a SPA, the end-user who knows Multi Pages expects the following features: Routing is the procedure that keeps the browser URL in sync with the content.
Using declarative routing, you can control the application's traffic information using the expression "the route should look like this..." and place components wherever you have a preference. In reality, it is a third-party library known for its simplicity.
What is React Router?
React itself is focused on building user interfaces, and it lacks a fully integrated routing solution. React Router is React's most popular routing library. It allows you to define paths in the same declarative style as most other libraries. A router allows your application to navigate by changing its browser's URL or browsing history while staying in synch with other elements.
Understanding routes
The matching logic to a component is delegated to the path-to-regexp library. With this behavior, you set which component should be displayed for a specific URL path.
It means that if you have, for example, an "about me" page and the path of this page is "/about-me," you need to assign a component that Reacts will render for that specific path.
What does React Router DOM do?
React Router DOM allows you to implement dynamic routing in web apps. React RouterDOM supports component-based routing according to the app's requirements and the framework. In contrast, the traditional routing architecture provides routing services in a configuration outside of a currently active app. React Router is the best solution for creating React Applications that run in the browser. React router DOM is the quickest way to create routing in React.
Let's dive in!
This tutorial is split out among multiple areas. Our first task is to a create React app and install React Router using npm. Now we'll get down to some basic features of the React Router. Each concept and system for constructing these routes will be discussed along the course.
The full code for the project is published at this GitHub repository. This tutorial presents concepts of using React routing, the basics of React, hooks, and testing.
Prerequisites
I tested the code in Node 14.17.3. I set up the project using Create React App. You will also need a basic knowledge of JavaScript, HTML & CSS add React to understand what is going on here, but if you need to learn React Router, you are familiar with those things.
As I mentioned before, you'll require the Node installed on your computer for this tutorial. Then you can follow these instructions to set up React project using Create React App.
Remove these files: reportWebVitals.js, index.css, logo.svg, App.css, and App.test.js -who needs tests??? But wait, we can add our own tests later, don't worry, I am just trolling you.
Change title and description in public/index.html and remove unnecessary comments. The final result should look like this:
1<!DOCTYPE html>
2<htmllang="en">3<head>4<metacharset="utf-8" />5<linkrel="icon"href="%PUBLIC_URL%/favicon.ico" />6<metaname="viewport"content="width=device-width, initial-scale=1" />7<metaname="theme-color"content="#000000" />8<meta9name="description"10content="React router tutorial"11 />12<linkrel="apple-touch-icon"href="%PUBLIC_URL%/logo192.png" />1314<linkrel="manifest"href="%PUBLIC_URL%/manifest.json" />15<title>React Router example</title>16</head>17<body>18<noscript>You need to enable JavaScript to run this app.</noscript>19<divid="root"></div>20</body>21</html>2223
To get React Router working in your App, you need to add a Router. Basically, it means that you need to wrap your app with a top-level router that makes all other React Router components and hooks work. A router is stateful, and it creates history with the initial location and subscribes to the URL.
React Router can subscribe to the URL changes thanks to the History object. Each user action that changes URL is kept in History Stack.
There are three types of those actions: PUSH, POP, and REPLACE.
PUSH - a new entry is added to the history stack
POP - it happens when a user click Browser's back or forward buttons
REPLACE - Replace action is similar to PUSH, but it replaces the current entry in the history stack instead of adding a new one
A location is an object built on top of a window. location object. In this object, you can find information about URL, and in general, it represents where a user is at the time.
There are three types of Routers in react-router-dom:
BrowserRouter - recommended for running React Router in a Web browser
HashRouter - is used for apps where the URL should not be sent to a server for some reason. It's not recommended to use the Hash router unless you absolutely have to.
MemoryRouter - the common case of using MemoryRouter is testing. It stores all information in an array.
We imported a NavLink component here from react-router-dom:
1import { NavLink } from"react-router-dom";
2
A NavLink component is a special type of the Link component with an additional feature. It can have an "active" class where the URL is the same as "to property.
A Link React component renders <a> tag with real href property. The difference about the real <a> tag is that React Router will handle navigation to specific locations when you use Link (and NavLink).
So in our app, even we haven't declared any routes yet, the URL is changed without page reloading thanks to React Router.
Besides, we imported there some Bootstrap stuff:
1import { Navbar, Container, Nav } from'react-bootstrap'2
The page should look like this:
Summarizing, we added three links: HomePage: /, Address book: /address, and Orders: /orders.
So we have a route that handles the "/" path and renders the App, a React component. Basically, nothing has changed in our app so far. Let's implement other routes.
React Router uses nested routes to provide the most detailed routing details inside child components. Those routes group your routing information directly into components to render other components.
By the finish of this step, you will have various ways of providing info. This is a little additional code, but the routes keep the child's parents in line. Not every project uses a nested route: some prefer an explicit list.
Nested routes allow you to build a complex system of routing. Each route defines a portion of the URL through segments, and a single URL can match multiple routes. Take a look:
Here is our main route:
1/
2
Here is the route for the address book:
1/address
2
And here is the route for address details
1/address/:addressId
2
So the route is built by three routes: / + address/ + :/addressId
Of course, we need to define two new components: AddressBook, and AddressDetails
src/routes/AddressBook/addressBook.js:
1import React from'react'23exportconst addressBook = () => {
4return<p>Address book will be here</p>5}
67exportdefault addressBook;
89
src/routes/AddressBook/index.js
1export { default } from'./addressBook';
2
Do the same for address details (and do not forget about importing these routes in index.js!)
That should work, but wait. If you go now for the address page, you will see that the address route is rendered, but it looks pretty the same as the index route, but we except that there will be a paragraph: Address book will be here.
To render the content of any child, you need to use the Outlet component that renders the next match in a set of matches.
Please import the Outlet React component to the App component:
On the right of navigation, there is a space for address details, but initially then is empty space. When you click on an address in navigation, you can see address details.
There is a way to add some improvements! Let's add a paragraph that says: "Please select an address." To do so that you can use another pretty cool feature of React Router called: Index route
Add this code to index.js to AddressBook route component:
1<Route
2 index
3 element={
4<p>Select an address.</p>5 }
6/>
7
Now, when you go to the address book, you can see "Select an address" text by default:
Let's do something similar for the home route:
1<Route
2 index
3 element={
4<>5<h2>Welcome in your account.</h2>6<p>Please use the navigation above to see Address book or your orders.</p>7</>8 }
9/>
10
React Routes provides a useSearchParams hook that allows you to read and modify a query part of a URL (q=). Let's use it to add some filtering to the App.
First import useSearchParams hook in the AddressBook React component ad get searchParams, and setSearchParams from it:
1import { useSearchParams } from"react-router-dom";
23// below in the compoonent body:45const [searchParams, setSearchParams] = useSearchParams();
6
Second, add a search form. To do so, add this code at the beginning of the return function:
1<Col sm="12">
2<nav>3<InputGroupsize="sm"className="mb-3">4<InputGroup.Textid="address-search">Search for an address</InputGroup.Text>5<FormControlaria-label="Search for an address"6aria-describedby="address-search"7value={searchParams.get("filter") || ""}
8onChange={event => {
9 const filter = event.target.value;
10 if (filter) {
11 setSearchParams({ filter });
12 } else {
13 setSearchParams({});
14 }
15 }} />
16</InputGroup>17</nav>18</Col>
19
A function bound on the onCahnge event sets the current input value to the URL query param.
Third, let's read the query param and filter addresses by it:
That code handles all routers not handled by other defined routes components. On the other hand, if no routes match, those elements will be rendered. Of course, you can use the react component as well.
A protected route is used to ensure only logged-in users can use some places on your site. Typically we create e a secure route component for someone in the system to use /admin when they attempt to connect. However, some aspects of React Router must first be covered.
Basically, you can create a special React component that will check if a user can go to a protected route or not.
Working Demo
Here you can see the demo of the application we developed with react-router:
React Router lets you handle all the routes in a React application. You can use it for a web app or even for React native app.
The router is one of the main React Router components, and for web apps, there is a BrowserRouter react component, a router implementation that uses HTML5 History API.
React Router provides other essential components are Routes, Route, Link, and NavLink.
Besides, there are a few hooks like useParams, useSearchParams, and useNavigate.
So react-router package provides just components and just hooks, and those all together allow you to create complex routing systems easily.
Did you like it? Share!
Each share supports and motivates me to create new content Thank you!
About the author
Marcin Kwiatkowski
Frontend developer, Certified Magento Full Stack Developer, writer, based in Poland. He has eight years of professional Software engineering experience. Privately, husband and father. He likes reading books, drawing, and walking through mountains.