Reader small image

You're reading from  React 18 Design Patterns and Best Practices - Fourth Edition

Product typeBook
Published inJul 2023
Reading LevelExpert
PublisherPackt
ISBN-139781803233109
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Carlos Santana Roldán
Carlos Santana Roldán
author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán

Right arrow

React Router

React is a library that provides a lot of useful building blocks for creating web applications, but it doesn’t include everything you might need out of the box. One key feature that React doesn’t provide is routing, which is the ability to handle URLs and navigate between different pages or views in a single-page application. For that, we turn to third-party libraries, and the most popular one for React is React Router.

In this chapter, we’ll explore React Router and learn how to use it to create dynamic routes and handle navigation in our React applications. By the end of this chapter, you’ll have a good understanding of how React Router works and how to use it effectively in your own projects.

In this chapter, we will cover the following topics:

  • Understanding the differences between the react-router, react-router-dom, and react-router-native packages
  • How to install and configure React Router
  • Adding the <...

Technical requirements

To complete this chapter, you will need the following:

  • Node.js 19+
  • Visual Studio Code

You can find the code for this chapter in the book’s GitHub repository at https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/tree/main/Chapter09.

Installing and configuring React Router

After you create a new React application using create-react-app, the first thing you need to do is to install React Router v6.x, using the following command:

npm install react-router-dom @types/react-router-dom

You are probably confused about why we are installing react-router-dom instead of react-router. React Router contains all the common components of react-router-dom and react-router-native. That means that if you are using React for the web, you should use react-router-dom, and if you are using React Native, you need to use react-router-native.

The react-router-dom package was created originally to contain version 4 and react-router uses version 3. The react-router-dom v6 package has some improvements over react-router. They are listed here:

  • Simplified route configuration: React Router v6 has introduced a more straightforward route configuration, eliminating the need for Switch and exact props. Routes are now implicitly...

Creating our sections

Let’s create some sections to test some basic routes. We need to create four stateless components (About, Contact, Home, and Error404) and name them as index.tsx in their directories.

You can add the following to the src/components/Home.tsx component:

const Home = () => (
<div className="Home">
  <h1>Home</h1>
</div>
)
export default Home

The src/components/About.tsx component can be created with the following:

const About = () => (
<div className="About">
  <h1>About</h1>
</div>
)
export default About

The following creates the src/components/Contact.tsx component:

const Contact = () => (
<div className="Contact">
  <h1>Contact</h1>
</div>
)
export default Contact

Finally, the src/components/Error404.tsx component is created as follows:

const Error404 = () => (
<div className="Error404">
 ...

Adding parameters to the routes

So far, you have learned how to use React Router for basic routes (one-level routes). Next, I will show you how to add some parameters to the routes and get them into your components.

For this example, we will create a Contacts component to display a list of contacts when we visit the /contacts route, but we will show the contact information (name, phone, and email) when the user visits /contacts/:contactId.

The first thing we need to do is to create our Contacts component. Let’s use the following skeleton: const Contacts = () => (

<div className="Contacts">
  <h1>Contacts</h1>
</div>
)
export default Contacts

Let’s use these CSS styles:

.Contacts ul {
  list-style: none;
  margin: 0;
  margin-bottom: 20px;
  padding: 0;
}
.Contacts ul li {
  padding: 10px;
}
.Contacts a {
  color: #555;
  text-decoration: none;
}
.Contacts a:hover {
  color: #ccc;
  text-decoration: none;
}
...

React Router v6.4

As mentioned at the beginning of this chapter, React Router v6.4 introduces a new way of implementing routes.

Let’s rewrite our last example to explore the differences. The first difference is that instead of using AppRoutes as we did previously, we will now add our routes directly to our App.tsx file. Let’s begin by modifying our main.tsx and removing AppRoutes:

import { createRoot } from 'react-dom/client'
import App from './App'
createRoot(document.getElementById('root') as HTMLElement).render(
<App />
)

Now, in our App.tsx file, we need to import some new functions from react-router-dom and load the components that will be rendered for each URL:

import { FC } from 'react'
import { 
  createBrowserRouter, 
  createRoutesFromElements, 
  Route, 
  Link, 
  Outlet, 
  RouterProvider 
} from 'react-router-dom'
import About from './components/About'
import Home from &apos...

Summary

Good job! By navigating React Router, you have acquired essential skills for installing, configuring, and managing routes, as well as incorporating parameters into nested routes. You will be able to create more dynamic and robust web applications using React Router by utilizing these capabilities. In addition, you have learned about the cutting-edge features of React Router v6.4, particularly its innovative use of loaders.

We are about to embark on the next chapter of this series, where we will explore the exciting new features introduced in React 18. By continuously learning and applying, you will become proficient in React.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 18 Design Patterns and Best Practices - Fourth Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781803233109
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán