Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React Key Concepts

You're reading from  React Key Concepts

Product type Book
Published in Dec 2022
Publisher Packt
ISBN-13 9781803234502
Pages 590 pages
Edition 1st Edition
Languages
Author (1):
Maximilian Schwarzmüller Maximilian Schwarzmüller
Profile icon Maximilian Schwarzmüller

Table of Contents (16) Chapters

Preface
1. React – What and Why 2. Understanding React Components and JSX 3. Components and Props 4. Working with Events and State 5. Rendering Lists and Conditional Content 6. Styling React Apps 7. Portals and Refs 8. Handling Side Effects 9. Behind the Scenes of React and Optimization Opportunities 10. Working with Complex State 11. Building Custom React Hooks 12. Multipage Apps with React Router 13. Managing Data with React Router 14. Next Steps and Further Resources Appendix

12. Multipage Apps with React Router

Learning Objectives

By the end of this chapter, you will be able to do the following:

– Build multipage single-page applications (and understand why this is not an oxymoron).

– Use the React Router package to load different React components for different URL paths.

– Create static and dynamic routes (and understand what routes are in the first place).

– Navigate the website user via both links and programmatic commands.

– Build nested page layouts.

Introduction

Having worked through the first eleven chapters of this book, you should now know how to build React components and web apps, as well as how to manage components and app-wide state, and how to share data between components (via props or context).

But even though you know how to compose a React website from multiple components, all these components are on the same single website page. Sure, you can display components and content conditionally, but users will never switch to a different page. This means that the URL path will never change; users will always stay on your-domain.com. Also, at this point in time, your React apps don't support any paths such as your-domain.com/products or your-domain.com/blog/latest.

Note

Uniform Resource Locators (URLs) are references to web resources. For example, https://academind.com/courses is a URL that points to a specific page of the author's website. In this example, academind.com is the domain name of the website...

One Page Is Not Enough

Having just a single page means that complex websites that would typically consist of multiple pages (e.g., an online shop with pages for products, orders, and more) become quite difficult to build with React. Without multiple pages, you have to fall back to state and conditional values to display different content on the screen.

But without changing URL paths, your website visitors can't share links to anything but the starting page of your website. Also, any conditionally loaded content will be lost when a new visitor visits that starting page. That will also be the case if users simply reload the page they're currently on. A reload fetches a new version of the page, and so any state (and therefore user interface) changes are lost.

For these reasons, you absolutely need a way of including multiple pages (with different URL paths) in a single React app for most React websites. Thanks to modern browser features and a highly popular third-party...

Getting Started with React Router and Defining Routes

React Router is a third-party React library that can be installed in any React project. Once installed, you can use various components in your code to enable the aforementioned features.

Inside your React project, the package is installed via this command:

npm install react-router-dom

Once installed, you can import and use various components (and Hooks) from that library.

To start supporting multiple pages in your React app, you need to set up routing by going through the following steps:

  1. Create different components for your different pages (e.g., Dashboard and Orders components).
  2. Use the BrowserRouter, Routes, and Route components from the React Router library to enable routing and define the routes that should be supported by the React app.

In this context, the term routing refers to the React app being able to load different components for different URL paths (e.g., different components for...

From Static to Dynamic Routes

Thus far, all examples have had two routes: / for the Dashboard component and /orders for the Orders component. But you can, of course, add as many routes as needed. If your website consists of 20 different pages, you can (and should) add 20 route definitions (i.e., 20 Route components) to your App component.

On most websites, however, you will also have some routes that can't be defined manually—because not all routes are known in advance.

Consider the example from before, enriched with additional components and some realistic dummy data:

Figure 12.8: A list of order items

Note

You can find the code for this example on GitHub at https://packt.link/KcDA6. In the code, you'll notice that many new components and style files were added. The code does not use any new features, though. It's just used to display a more realistic user interface and output some dummy data.

In the preceding screenshot,...

Redirecting

Thus far, all the explored navigation options (links and programmatic navigation) forward a user to a specific page.

In most cases, that's the intended behavior. But in some cases, the goal is to redirect a user instead of forwarding them.

The difference is subtle but important. When a user is forwarded, they can use the browser's navigation buttons (Back and Forward) to go back to the previous page or forward to the page they came from. For redirects, that's not possible. Whenever a user is redirected to a specific page (rather than forwarded), they can't use the Back button to return to the previous page.

Redirecting users can, for example, be useful for ensuring that users can't go back to a login page after authenticating successfully.

When using React Router, the default behavior is to forward users. But you can easily switch to redirecting by adding the special replace prop to the Link (or NavLink) components, as follows:

...

Summary and Key Takeaways

  • Routing is a key feature for many React apps.
  • With routing, users can visit multiple pages despite being on an SPA.
  • The most common package that helps with routing is the React Router library (react-router-dom).
  • Routes are defined with the help of the Routes and Route components (typically in the App component, but you can do it anywhere).
  • The Route component takes a path (for which the route should become active) and an element (the content that should be displayed) prop.
  • Users can navigate between routes by manually changing the URL path, by clicking links or because of programmatic navigation.
  • Internal links (i.e., links leading to application routes defined by you) should be created via the Link or NavLink components, while links to external resources use the standard <a> element.
  • Programmatic navigation is triggered via the navigate() function, which is yielded by the useNavigate() Hook.
  • You can define static...

Apply What You Learned

Apply your knowledge about routing to the following activities.

Activity 12.1: Creating a Basic Three-Page Website

In this activity, your task is to create a basic first version for a brand-new online shop website. The website must support three main pages:

  • A welcome page
  • A products overview page that shows a list of available products
  • A product details page, which allows users to explore product details

Final website styling, content, and data will be added by other teams, but you should provide some dummy data and default styling. You must also add a main navigation bar at the top of each website page.

The finished pages should look like this:

Figure 12.12: The final welcome page

Figure 12.13: The final products page

Figure 12.14: The final product details page

Note

For this activity, you can, of course, write all CSS styles on your own. But if you want...

lock icon The rest of the chapter is locked
You have been reading a chapter from
React Key Concepts
Published in: Dec 2022 Publisher: Packt ISBN-13: 9781803234502
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.
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 $15.99/month. Cancel anytime}