Hello! Welcome to the first lesson in our new module, Client-Side Routing with React Router.
In the previous modules, you've mastered the art of building isolated, stateful, and logical components. We concluded by exploring how to compose custom hooks to create powerful, domain-specific logic. Now, your components are ready, but they all live on a single, static page. To build a true web application, users need to navigate between different views—a home page, an "about" section, a user dashboard, and so on.
This is where client-side routing comes in. Today's lesson directly addresses our first learning outcome for this module: Set up and configure React Router in a TypeScript-based React application. We will lay the foundational plumbing that allows a single-page React application to have multiple "pages" or views, all managed on the client.
What is Client-Side Routing?
Before we write any code, it's crucial to understand what problem we're solving. In a traditional multi-page website, clicking a link sends a request to a server, which then responds with a completely new HTML document. This results in a full page refresh.
In a Single Page Application (SPA) like the ones we build with React, the server sends the entire application (a single index.html file, along with JavaScript and CSS) just once. From then on, when a user navigates, the "page" change is handled by JavaScript in the browser. The URL in the address bar is updated, and React swaps out components to display the new view, all without a full-page reload. This creates a much faster and smoother user experience.
The following diagram illustrates this key difference:

React Router is the most popular library for implementing this client-side routing behavior in React applications. It provides the tools to map specific URLs to your components, keeping your UI and the browser's address bar in sync.
1. Installation
Our first step is to add React Router to our Vite project. We will install react-router-dom, which is the specific package for web applications.
It's a common point of confusion, so it's worth highlighting: react-router contains the core routing logic, while react-router-dom includes everything from react-router plus additional components and hooks specifically for browser-based environments (like handling the URL in the address bar). For web development, you always want to install and import from react-router-dom.
Since we are using TypeScript, we'll also install the corresponding type definitions.
React Typescript 2023 - 16. React Router
This short video from Teddy Smith demonstrates the installation process. It also briefly touches on the distinction between react-router and react-router-dom.
Watch from 01:02 to 02:01. Follow along to install the necessary packages in your project terminal.
To summarize the video, run the following commands in your project's terminal:
npm install react-router-dom
npm install -D @types/react-router-dom
2. The Core of Modern React Router: createBrowserRouter
The modern approach to routing in React Router (since v6.4) is to use a data router, and the recommended way to create one for browser-based applications is with the createBrowserRouter function.
As your background is in engineering, you might appreciate the design principles behind this. The official documentation explains that this API is designed to be created outside the React component tree. This allows for a statically defined set of routes, which is a powerful pattern that enables more advanced features like data loading and actions before a component even renders (which we will explore later in the course).
The official React Router documentation provides a concise explanation of createBrowserRouter and why it is the recommended choice.
Please read the introductory section of this documentation page. Focus on understanding that createBrowserRouter uses the DOM History API and is the entry point for React Router's modern data APIs.
3. Configuration Steps
Now, let's configure our application. This process involves two main steps:
- Defining our routes using
createBrowserRouter. - Making the router available to our application using a
<RouterProvider>component.
Let's walk through this by modifying our main entry point, src/main.tsx.
Step 1: Create Placeholder Page Components
First, let's create a couple of simple components to act as our pages.
Create a new folder src/pages. Inside it, create two files:
src/pages/HomePage.tsx
import React from 'react';
export function HomePage() {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to our application!</p>
</div>
);
}
src/pages/AboutPage.tsx
import React from 'react';
export function AboutPage() {
return (
<div>
<h1>About Page</h1>
<p>This is a sample React application with client-side routing.</p>
</div>
);
}
Note: In a real app, you might have your App component serve as a layout wrapper, but for this initial setup, we'll route directly to distinct page components to keep it simple.
Step 2: Define Routes in main.tsx
Now, open src/main.tsx. We will import createBrowserRouter and our new page components, then define our route configuration.
A route configuration is an array of route objects. Each object must have at least a path and an element to render for that path.
// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
// 1. Import the necessary functions and components
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
// Import our page components
import { HomePage } from './pages/HomePage';
import { AboutPage } from './pages/AboutPage';
// 2. Define the application's routes
const router = createBrowserRouter([
{
path: '/',
element: <HomePage />,
},
{
path: '/about',
element: <AboutPage />,
},
]);
// 3. Render the app using the RouterProvider
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
Let's break down what's happening here:
- We import
createBrowserRouterto build our router andRouterProviderto connect it to our app. - We create a
routerinstance by callingcreateBrowserRouterwith an array of route objects. The object{ path: '/', element: <HomePage /> }tells React Router: "when the URL path is exactly/, render the<HomePage />component." - Instead of rendering our old
<App />component directly, we now render<RouterProvider />and pass ourrouterconfiguration to it as a prop. TheRouterProvideruses React's Context API internally to make all the routing information and hooks available to any component nested within it.
A Closer Look at the Setup
This configuration model is powerful and declarative. The following video provides another walkthrough of this exact setup, reinforcing the concepts of createBrowserRouter and RouterProvider.
React Router - Complete Tutorial
This clip from the 'React Router - Complete Tutorial' by Cosden Solutions offers an excellent, detailed explanation of configuring the browser router.
Watch from 01:19 to 05:44. The video clearly explains how to import createBrowserRouter and RouterProvider, define route objects, and replace the static component rendering in main.tsx.
Now, if you run your application (npm run dev) and navigate to http://localhost:5173/ in your browser, you should see the HomePage. If you manually change the URL to http://localhost:5173/about, the view will change to the AboutPage without a full page refresh. Congratulations, you've successfully configured client-side routing!
Test your understanding!
Let's expand our application. First, create a new file src/pages/ContactPage.tsx with a simple component inside it. Then, modify your router configuration in main.tsx to render this new component when the user navigates to the /contact path.
Show answer
-
Create the component file
src/pages/ContactPage.tsx:import React from 'react'; export function ContactPage() { return ( <div> <h1>Contact Us</h1> <p>You can reach us at contact@example.com.</p> </div> ); } -
Update
main.tsx:// src/main.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import { createBrowserRouter, RouterProvider } from 'react-router-dom'; // Import the page components import { HomePage } from './pages/HomePage'; import { AboutPage } from './pages/AboutPage'; import { ContactPage } from './pages/ContactPage'; // Import the new page // Define the application's routes const router = createBrowserRouter([ { path: '/', element: <HomePage />, }, { path: '/about', element: <AboutPage />, }, { path: '/contact', // Add the new route object element: <ContactPage />, }, ]); ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode> );
A Complete Minimal Example
To see all these pieces working together in a slightly more structured way, it's helpful to review a complete, minimal example. The following article provides a fantastic, production-ready pattern.
Minimal Working Example (TypeScript)
This article from dev.to, 'React Router: Navigate on Button Click with createBrowserRouter', starts with a perfect minimal working example for setting up a router with TypeScript.
Focus only on the code block under the '1) Minimal Working Example (TypeScript)' section, specifically the main.tsx file. Notice how it follows the exact pattern we just implemented. The other files like AppLayout.tsx give a small preview of how you might structure shared layouts, a topic we'll cover soon.
This example introduces the concept of a layout route (AppLayout) with an <Outlet />. This is a sneak peek into our upcoming lessons, where we'll learn how to create shared UI (like headers and footers) that persists across different pages.
Conclusion
In this lesson, you've taken the first and most critical step in building a multi-view React application. You've set up the routing infrastructure that will serve as the backbone for user navigation.
Key Takeaways:
- Client-side routing creates a fast, seamless SPA experience by handling navigation in the browser without full page reloads.
- React Router is the standard library for implementing routing in React. For web apps, you always use the
react-router-dompackage. - The modern, recommended setup uses
createBrowserRouterto define a static array of route objects. - The
<RouterProvider>component takes the router configuration and makes it available to your entire application via React's Context. - A basic route object consists of a
path(the URL) and anelement(the component to render).
Preview of the Next Lesson:
Our application now understands different URLs, but users can't navigate between them without manually typing in the address bar. In the next lesson, we will make our application interactive by learning how to implement navigation between routes using the <Link> and <NavLink> components.