React Router

While Create React App doesn’t include page routing out-of-the-box, React Router is the most popular solution for handling routing in React applications.

Tutorials dojo strip

Adding React Router to Your Project

To incorporate React Router into your application, execute the following command in your terminal from the root directory of your project:

JavaScript

Note: This tutorial uses React Router v6. If you’re upgrading from v5, use the @latest flag:

JavaScript

Folder Structure

To create a multi-page application, we’ll organize our files as follows. In the src directory, create a pages folder with the following files:

  • src/pages/:
  • Layout.js
  • Home.js
  • Articles.js
  • ContactMe.js
  • NotFound.js

Each of these files will contain a basic React component.

Basic Usage

Next, we’ll use our Router in the index.js file.

Use React Router to navigate to different pages based on the URL:

JavaScript

Example Explanation

  • First, we wrap our content with <BrowserRouter>. Then, we define our <Routes>. An application can have multiple <Routes> components, but our basic example uses just one.
  • <Route> elements can be nested. The first <Route> has a path of / and renders the Layout component. The nested <Route> elements inherit and extend the parent route. For instance, the articles path becomes /articles.
  • The Home component’s route has no path but includes an index attribute, designating it as the default route for the parent path, which is /. Setting the path to * acts as a catch-all for undefined URLs, which is useful for a 404 error page.

Pages / Components

The Layout component includes <Outlet> and <Link> elements. The <Outlet> renders the matched child route, while <Link> is used to set the URL and maintain browsing history. For internal navigation, we use <Link> instead of <a href="">.

The “layout route” is a shared component that displays common content across all pages, like a navigation menu.

Layout.js:

JavaScript

Home.js:

JavaScript

Articles.js:

JavaScript

ContactMe.js:

JavaScript

NotFound.js:

JavaScript

Tutorials dojo strip