Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 48

Route to Components: URL Mapping in React

Recommended resources

Hello! Welcome back.

In our last lesson, we successfully installed and configured React Router. We laid the groundwork by wrapping our application in <BrowserRouter> and defining our very first route. This was the equivalent of setting up the routing engine. Now, it's time to build the map.

This lesson directly addresses the learning outcome: Define application routes by mapping URL paths to specific React components. We will expand on our single route to create a navigation structure with multiple "pages," which is a fundamental step in building any real-world application.

For you, coming from Laravel, this process is conceptually similar to defining your routes in a file like web.php. Just as you map a URL to a controller method in Laravel, here we will map a URL path to a specific React component.

1. Creating Your Page Components

Before we can define routes, we need the components that will act as our pages. It's a common convention to organize these in a dedicated src/pages directory to keep your project structure clean.

Let's create three simple page components and a "not found" page.

HomePage:

// src/pages/HomePage.jsx
import React from 'react';

const HomePage = () => {
  return <h1>Home Page</h1>;
};

export default HomePage;

AboutPage:

// src/pages/AboutPage.jsx
import React from 'react';

const AboutPage = () => {
  return <h1>About Us</h1>;
};

export default AboutPage;

ProductsPage:

// src/pages/ProductsPage.jsx
import React from 'react';

const ProductsPage = () => {
  return <h1>Our Products</h1>;
};

export default ProductsPage;

NotFoundPage:

// src/pages/NotFoundPage.jsx
import React from 'react';

const NotFoundPage = () => {
  return <h1>404 - Page Not Found</h1>;
};

export default NotFoundPage;

Now we have the destinations for our routes.


2. Mapping Paths to Components

With our page components ready, we can now map URL paths to them in App.jsx. We'll use the <Routes> and <Route> components from react-router-dom.

  • <Routes>: This component acts as a container for all your individual routes. It intelligently examines the current URL and renders the best matching <Route>.
  • <Route>: This is where the mapping happens. It takes two essential props:
    • path: A string that defines the URL path to match (e.g., "/", "/about").
    • element: The React component to render when the path matches (e.g., <HomePage />).

The following video provides an excellent walkthrough of this entire process. It shows how to import the necessary components and build out the routing structure.

React Router V6 Tutorial - Routes, Redirecting, UseNavigate, UseParams...

This video from PedroTech clearly demonstrates how to set up multiple routes and a 'catch-all' route for pages that don't exist.

Watch from 05:29 to 11:11. Focus on these key steps: Defining Multiple Routes (05:29 - 09:26): Pay attention to how the <Route> component is used repeatedly within <Routes>. Notice the path and element props that connect a URL to a specific page component. Creating a 404 Page (09:26 - 11:11): Observe the special syntax path="*". This is the 'catch-all' route that renders an error page when no other route matches the URL.

As the video demonstrates, defining your routes is a declarative process. You are describing what the UI should look like for a given URL.


3. Understanding the Route Components

To solidify what you saw in the video, let's look at a textual explanation of the core components.

A Complete Guide to React Router: Everything You Need to Know

This article from Fireship provides a concise summary of the main React Router components. It's a great reference to quickly understand the roles of Route and Routes.

Read the sections titled Route, Routes, and Catch all (404) Pages. These sections clearly explain the purpose of each component and reinforce the path="*" syntax for a 404 page.

A key takeaway from modern React Router (version 6) is that the <Routes> component is intelligent. It analyzes all its child <Route>s and picks the most specific match. This means you don't have to worry about ordering your routes, unlike in some older routing systems. A path like /products is considered more specific than /products/:id, which is more specific than *.


4. Putting It All Together

Let's update your App.jsx file to include all the routes we've discussed. Make sure you import the page components you created earlier.

// src/App.jsx
import React from 'react';
import { Routes, Route } from 'react-router-dom';

// Import your page components
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import ProductsPage from './pages/ProductsPage';
import NotFoundPage from './pages/NotFoundPage';

function App() {
  return (
    <div>
      {/* You could have a Navbar component here, we'll build that next! */}
      <main>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/about" element={<AboutPage />} />
          <Route path="/products" element={<ProductsPage />} />

          {/* This 'catch-all' route must be the last one if you were using older versions, 
              but in v6 the router is smart enough to pick the best match regardless of order. 
              It will only match if no other routes above do. */}
          <Route path="*" element={<NotFoundPage />} />
        </Routes>
      </main>
      {/* You could have a Footer component here */}
    </div>
  );
}

export default App;

After setting this up, run your development server. You should now be able to manually navigate to http://localhost:5173/, http://localhost:5173/about, and http://localhost:5173/products in your browser and see the corresponding components render. If you try a URL that doesn't exist, like http://localhost:5173/contact, you will see the NotFoundPage component.


Conclusion

You have now successfully created the navigation blueprint for your application. This is a crucial skill for building any SPA.

Key Takeaways:

  • Application routes are defined inside the <Routes> component.
  • Each route is a <Route> component that maps a URL path to a React element.
  • A "catch-all" route with path="*" is used to handle invalid URLs and display a "404 Not Found" page.
  • In React Router v6, the router intelligently ranks routes by specificity, so you don't need to worry about the order of your <Route> definitions.

Preview of the Next Lesson:
Our pages are now accessible via their URLs, but users need a way to navigate between them without manually typing into the address bar. In the next lesson, we will learn how to create clickable navigation elements using the <Link> and <NavLink> components from React Router.