Hello! Let's dive into the second lesson of our module on client-side routing.
In our last session, we set up the foundational plumbing for routing in our React application. We learned about the modern, recommended approach using createBrowserRouter to define a route configuration as a JavaScript object array, and RouterProvider to make that configuration active. This powerful setup is the gateway to advanced features like data loading, which we'll explore later in the course.
Today, we'll explore a different, yet very common and more visually declarative, way to define our application's routes. This lesson focuses on the learning outcome: Define application routes using <Route> components for path matching. We will learn how to use JSX components provided by React Router to build our route hierarchy, a pattern you will frequently encounter in existing codebases and tutorials.
Two Approaches to Routing Configuration
React Router offers two primary ways to configure your routes:
-
Object-based (Data Routers): This is the method we learned in the last lesson. You define an array of route objects and pass it to
createBrowserRouter. This is the recommended approach for new projects, as it enables all of React Router's newest features. -
Component-based: In this approach, you wrap your application in a
<BrowserRouter>component. Then, within your component tree, you use the<Routes>and<Route>JSX components to define your routing logic.
While the object-based approach is the future, the component-based approach is intuitive, widely used, and essential to understand. Today, we'll refactor our application to use this pattern.
1. Setting Up with <BrowserRouter>
First, let's adjust our main.tsx to use the component-based setup. This involves replacing createBrowserRouter and <RouterProvider> with the <BrowserRouter> component.
<BrowserRouter> is a component that uses the HTML5 History API (the same one used by createBrowserRouter) to keep your UI in sync with the URL. It creates a React context that provides routing information to all its descendant components.
Let's modify src/main.tsx:
Previous src/main.tsx:
const router = createBrowserRouter([
{ path: '/', element: <HomePage /> },
{ path: '/about', element: <AboutPage /> },
]);
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
New src/main.tsx:
// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
// 1. Import BrowserRouter instead of createBrowserRouter/RouterProvider
import { BrowserRouter } from 'react-router-dom';
// 2. We'll move the route definitions into the App component, so import it
import App from './App'; // Assuming your main App component is in App.tsx
import './index.css'; // Or your main css file
// 3. Wrap the App component with BrowserRouter
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
With this change, our entire application now has access to the routing context. The responsibility for defining the actual routes now shifts to our <App /> component.
2. Defining Routes with JSX: <Routes> and <Route>
Now for the core of today's lesson. Inside our App component, we will use two new components from react-router-dom:
<Routes>: This component acts as a container. It examines the current URL and searches through its children<Route>elements to find the best match.<Route>: This is where the actual mapping happens. You use it to define a single route that connects a URLpathto a componentelement.
The video below provides an excellent demonstration of setting up these components.
Learn React Router v6 In 45 Minutes
In this clip from 'Learn React Router v6 In 45 Minutes', the instructor from Web Dev Simplified clearly demonstrates how to use the <Routes> and <Route> components to define the paths for a simple application.
Watch from 01:45 to 04:17. Pay close attention to how <Routes> wraps all the individual <Route> components and how each <Route> uses the path and element props.
Following the video's example, let's create our route structure in App.tsx. We'll also need our page components from the last lesson.
src/App.tsx
import { Routes, Route } from 'react-router-dom';
import { HomePage } from './pages/HomePage';
import { AboutPage } from './pages/AboutPage';
function App() {
return (
<div>
{/* You might have a site-wide header or navigation bar here */}
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</div>
);
}
export default App;
With this setup, when the URL is /, React Router will render <HomePage />. When it's /about, it will render <AboutPage />. This JSX tree is a very readable and declarative way to represent your application's page structure.
3. Understanding Path Matching
React Router v6 has an intelligent algorithm for path matching. It's designed to "just work" in most cases by picking the most specific path that matches the URL. Let's explore some key path patterns.
Basic and Catch-All Routes
As we've seen, path="/about" is a static path that matches exactly that URL. But what if a user navigates to a URL we haven't defined, like /contact? Right now, nothing would render inside our <Routes> block. We can handle this gracefully by creating a "Not Found" or "404" page.
React Router provides a special path value, *, which acts as a catch-all. It will match any URL that hasn't been matched by other, more specific routes.
Defining Routes in React Router v6
The article 'Complete Guide to React Router v6' provides a clear, written example of how to construct basic routes.
Read the section 'Defining Routes in React Router v6', focusing on 'Creating Basic Routes'. Note the syntax <Route path="..." element={<... />} /> and the explanation that element is used for JSX rendering, replacing the older component prop.
Let's add a NotFoundPage component and a catch-all route.
src/pages/NotFoundPage.tsx
export function NotFoundPage() {
return (
<div>
<h1>404 - Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
</div>
);
}
Updated src/App.tsx
import { Routes, Route } from 'react-router-dom';
import { HomePage } from './pages/HomePage';
import { AboutPage } from './pages/AboutPage';
import { NotFoundPage } from './pages/NotFoundPage'; // Import it
function App() {
return (
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="*" element={<NotFoundPage />} /> {/* Add the catch-all */}
</Routes>
);
}
export default App;
Now, navigating to any undefined path (e.g., /asdf) will render our NotFoundPage.
Dynamic Route Segments
Often, you need routes that follow a pattern. For example, in a blog, you might have URLs like /posts/1, /posts/2, and so on. Instead of defining a route for every single post, you can define a route with a dynamic segment.
You create a dynamic segment by prefixing a path segment with a colon (:). For example: path="/posts/:postId". Here, postId is a URL parameter. This path will match /posts/1, /posts/hello-world, or any other value in that position.
We will learn how to access the value of postId inside your component in a later lesson. For now, the key is to understand how this pattern affects path matching.
Route Specificity
What happens if you have two routes that could both potentially match a URL?
<Routes>
<Route path="/books/:id" element={<BookPage />} />
<Route path="/books/new" element={<NewBookPage />} />
</Routes>
If you navigate to /books/new, both patterns technically match (new could be considered an :id). React Router v6 is smart enough to resolve this ambiguity. It has a ranking algorithm that prioritizes more specific, static paths over dynamic ones. In this case, it will correctly match /books/new to the <NewBookPage /> route. You no longer need to worry about the order of your <Route> elements like in previous versions.
Learn React Router v6 In 45 Minutes
This next clip from the Web Dev Simplified video explains both route specificity and how to set up a catch-all route.
Watch from 14:19 to 16:42. This section clearly explains how React Router prioritizes hard-coded paths (like /books/new) over dynamic ones (/books/:id) and demonstrates implementing a catch-all route for 404 pages.
Test your understanding!
Let's say you're building an e-commerce site. You need the following pages:
- A homepage at
/. - A product listing page at
/products. - A specific product detail page at
/products/:productId. - A user's shopping cart page at
/cart.
Assuming you have components named HomePage, ProductListPage, ProductDetailPage, and CartPage, write the JSX for the <Routes> block to implement this structure.
Show answer
import { Routes, Route } from 'react-router-dom';
import { HomePage } from './pages/HomePage';
import { ProductListPage } from './pages/ProductListPage';
import { ProductDetailPage } from './pages/ProductDetailPage';
import { CartPage } from './pages/CartPage';
import { NotFoundPage } from './pages/NotFoundPage';
// ... inside your App component's return statement
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/products" element={<ProductListPage />} />
<Route path="/products/:productId" element={<ProductDetailPage />} />
<Route path="/cart" element={<CartPage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
This structure correctly defines a static route for the product list and a dynamic route for individual product details, alongside the other static routes.
Conclusion
In this lesson, we pivoted to the component-based approach for defining routes, which provides a declarative and highly readable way to structure your application's navigation. While our setup in main.tsx changed, the core concepts of paths and elements remain the same.
Key Takeaways:
- React Router can be configured using a component-based pattern by wrapping your app in
<BrowserRouter>and defining routes with<Routes>and<Route>JSX components. - The
<Routes>component intelligently selects the best-matching<Route>for the current URL. - The
<Route>component maps apathto anelement. - Paths can be static (
/about), dynamic (/users/:id), or a catch-all (*) for handling 404s. - React Router v6 automatically handles route specificity, preferring static paths over dynamic ones.
Preview of the Next Lesson:
Our application now has a well-defined set of pages, but users still can't navigate between them without manually editing the URL. In the next lesson, Implement navigation between routes using the <Link> and <NavLink> components, we will add clickable links to create a truly interactive navigation experience.