Learn React · 9/13

Routing: Building Single Page Applications (SPAs)

8 min read

Routing: Building Single Page Applications (SPAs)

Welcome, future React expert! 🚀 Today, we're diving into one of the most crucial concepts in modern web development: Routing. Specifically, we'll be exploring how to build Single Page Applications (SPAs) using the incredibly popular React Router library.

Ever noticed how some websites feel incredibly fast and fluid, almost like a native desktop or mobile app? Chances are, you were interacting with a Single Page Application.

What's the Deal with Single Page Applications (SPAs)?

In a traditional multi-page application, every time you click a link, your browser sends a request to a server, which then sends back a brand new HTML page. This full-page reload can be slow and feel a bit clunky.

An SPA, on the other hand, loads a single HTML page and then dynamically updates the content as the user interacts with it. This creates a much smoother and more responsive user experience because we're no longer reloading the entire page. Think about web applications you use daily like Gmail, Google Maps, or Netflix; they all provide this seamless experience.

The Problem: If we only have one page, how do we create the illusion of multiple pages? How do we handle different URLs like /about or /contact? This is where the magic of client-side routing comes in, and for React, the go-to solution is React Router.


1. Introduction to React Router

So, what exactly is this "React Router" we speak of? Imagine you're a tour guide in a vast museum (your web application). Your job is to guide visitors (users) to different exhibits (components) based on the path they want to take. React Router is your trusty map and set of directions. It's a standard library for routing in React that allows you to synchronize the UI with the URL.

Why do we need it? React, by itself, doesn't have a built-in router. It's a library for building user interfaces, not for handling navigation. React Router fills this gap by providing a collection of navigational components that you can use in your React application.

Installation 🛠️

Let's get our hands dirty! To start using React Router, you need to add it to your project. The most common package is react-router-dom, which is specifically for web applications.

Open your project's terminal and run one of the following commands:

Using npm:

bash
npm install react-router-dom

Using Yarn:

bash
yarn add react-router-dom

A funny thought: Installing react-router-dom is like giving your app a GPS. Before, it was just a single, stationary location. Now, it can have different addresses and know how to get to each one!

To make React Router available to your entire application, you need to wrap your root component (usually App) with a <BrowserRouter> component in your main entry file (typically src/index.js or src/main.jsx).

jsx
// src/index.js or src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

By wrapping your app in <BrowserRouter>, you're enabling the routing capabilities for all the components within it.


2. Setting up Routes and Navigation (Link and NavLink)

Now that we have our GPS installed, it's time to define some addresses (routes) and create some navigation signs (links).

Defining Our Routes

In your main App component, you'll use the <Routes> and <Route> components to define the different paths of your application and which component should render for each path.

  • <Routes>: This component is a container for all your individual routes.
  • <Route>: This is where you define a single route. It has two important props:
    • path: The URL path you want to match.
    • element: The React component that should be rendered when the path matches.

Let's imagine we're building a simple website with a Home page, an About page, and a Contact page. Here's how you'd set up the routes:

jsx
// src/App.js
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';

function App() {
  return (
    <div>
      {/* Navigation links will go here */}
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </div>
  );
}

export default App;

Creating Navigation: <Link> vs. <NavLink>

You might be tempted to use a regular <a> tag for navigation, but that would cause a full-page reload, defeating the purpose of our SPA! Instead, React Router provides us with the <Link> component.

The <Link> component is a simple way to create navigation links. It takes a to prop that specifies the destination URL.

For creating a navigation menu, <NavLink> is often the better choice. It's a special version of <Link> that knows whether or not it is "active". This is incredibly useful for styling the currently selected link, providing visual feedback to the user.

Let's add a navigation bar to our App.js:

jsx
// src/App.js
import { Routes, Route, Link, NavLink } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import './App.css'; // Let's assume we have some basic styling

function App() {
  return (
    <div>
      <nav>
        <ul>
          <li>
            <NavLink to="/" className={({ isActive }) => (isActive ? 'active' : '')}>
              Home
            </NavLink>
          </li>
          <li>
            <NavLink to="/about" className={({ isActive }) => (isActive ? 'active' : '')}>
              About
            </NavLink>
          </li>
          <li>
            <NavLink to="/contact" className={({ isActive }) => (isActive ? 'active' : '')}>
              Contact
            </NavLink>
          </li>
        </ul>
      </nav>

      <hr />

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </div>
  );
}

export default App;

In the example above, we're using a function in the className prop of <NavLink>. This function receives an object with an isActive property, which we can use to conditionally apply a CSS class.


3. Dynamic Routing with URL Parameters (useParams)

Our website is looking good, but what if we have content that changes based on the URL? For instance, a blog with many posts, or an e-commerce site with thousands of products. We can't create a static route for every single one!

This is where dynamic routing comes to the rescue. We can create a route that accepts a parameter.

The Problem: How do we create routes for a potentially infinite number of items, like user profiles or blog posts, without manually defining each one?

The Solution: URL parameters! We can define a route with a placeholder, and then access that placeholder's value in our component.

Let's add a blog to our site. We'll have a main blog page that lists posts, and when a user clicks on a post, they'll be taken to a URL like /blog/my-first-post.

First, let's define the dynamic route in App.js:

jsx
// src/App.js - (inside the <Routes> component)
import BlogPost from './pages/BlogPost';

// ... other routes
<Route path="/blog/:postId" element={<BlogPost />} />

The :postId part is a URL parameter. It's a placeholder for the actual post ID.

Now, inside our BlogPost component, we can access the value of postId using the useParams hook. The useParams hook returns an object of key/value pairs of the dynamic params from the current URL.

jsx
// src/pages/BlogPost.js
import React from 'react';
import { useParams } from 'react-router-dom';

function BlogPost() {
  const { postId } = useParams();

  // Here, you would typically fetch the blog post data based on the postId
  // For this example, we'll just display it.

  return (
    <div>
      <h2>Blog Post</h2>
      <p>Now showing post with ID: <strong>{postId}</strong></p>
    </div>
  );
}

export default BlogPost;

If you navigate to /blog/hello-world, the postId will be "hello-world". If you go to /blog/123, postId will be "123". Pretty cool, right? It's like having a fill-in-the-blank for your URLs.


4. Programmatic Navigation (useNavigate)

Sometimes, you need to navigate the user without them clicking on a link. For example, after a user successfully logs in or submits a form, you'll want to redirect them to another page.

The Problem: How do we trigger navigation based on an event or a state change in our application?

The Solution: The useNavigate hook! This hook, introduced in React Router v6, gives you a function that you can call to navigate programmatically.

Let's imagine a login form. After a successful login, we want to redirect the user to their dashboard.

Here's how you can use useNavigate:

  1. Import the useNavigate hook from react-router-dom.
  2. Call it inside your component to get the navigate function.
  3. Call navigate with the path you want to go to.
jsx
// src/components/LoginForm.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';

function LoginForm() {
  const navigate = useNavigate();
  const [username, setUsername] = useState('');

  const handleLogin = (e) => {
    e.preventDefault();
    // In a real app, you would have authentication logic here
    if (username.trim() !== '') {
      console.log('Login successful!');
      // Redirect to the dashboard
      navigate('/dashboard');
    }
  };

  return (
    <form onSubmit={handleLogin}>
      <input
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="Enter username"
      />
      <button type="submit">Login</button>
    </form>
  );
}

export default LoginForm;

The navigate function can also take a second argument, an object with options. A common one is { replace: true }, which replaces the current entry in the history stack instead of adding a new one. This is useful for login pages so the user can't click the back button to go back to the login screen after they've logged in.

You can also navigate back and forward in the history stack by passing a number to navigate. For example, navigate(-1) is the same as clicking the browser's back button.

And that's a wrap on the fundamentals of React Router! You now have the power to create dynamic, multi-page-feeling applications with the speed and fluidity of a Single Page Application. Go forth and build amazing user experiences! 🎉

References for Extra Reading

Challenge

You are tasked with setting up the client-side routing for a new React application. You have been provided with several component stubs. Your goal is to wire them up using React Router to create a functional single-page application.

Requirements:

  1. In the App component, configure the application's routes within a <Routes> container.

    • The root path / should render the Home component.
    • The path /about should render the About component.
    • The path /login should render the Login component.
    • The path /dashboard should render the Dashboard component.
    • Implement a dynamic route for user profiles at /profile/:username that renders the Profile component.
  2. Above the <Routes> container in App.js, create a navigation header.

    • Use <NavLink> to create links to "Home" (/) and "About" (/about).
    • When a NavLink is active, it should be assigned the CSS class active-link.
  3. In the Profile component:

    • Extract the username parameter from the URL.
    • Display the extracted username inside the <h1> tag, formatted as: Profile for: [username].
  4. In the Login component:

    • Implement the handleLogin function.
    • When the "Log In and Go to Dashboard" button is clicked, it should programmatically navigate the user to the /dashboard route.
    • This navigation action should replace the /login route in the browser's history, preventing the user from navigating back to the login page using the back button.

Note: Assume the root of your application is already wrapped in <BrowserRouter>.

Expected result

Your final code should correctly implement the routing and navigation logic using react-router-dom.

  • The App component should import Routes, Route, and NavLink.
  • Inside App, the <nav> element should contain two <NavLink> components pointing to / and /about. Each should have a className prop that accepts a function, like className={({ isActive }) => isActive ? 'active-link' : ''}.
  • Below the <nav>, there should be a <Routes> component containing five <Route> definitions:
    • <Route path='/' element={<Home />} />
    • <Route path='/about' element={<About />} />
    • <Route path='/login' element={<Login />} />
    • <Route path='/dashboard' element={<Dashboard />} />
    • A dynamic route: <Route path='/profile/:username' element={<Profile />} />
  • The Profile component should import and use the useParams hook to get the username from the URL. The h1 should display this dynamic value.
  • The Login component should import and use the useNavigate hook. The handleLogin function should call navigate('/dashboard', { replace: true }).
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.