React Router: Client-Side Navigation

Build fast, multi-page web applications without ever leaving the page. Welcome to the world of client-side routing.

🚀

Welcome! Let's build an app with multiple pages, but without slow, full-page reloads.

// Let's build a Single-Page App (SPA)!

The <Route> Component: The URL Matchmaker

The `<Route>` component is the heart of React Router. It connects a specific URL path to one of your components. When the browser's URL matches the `path` prop of a `<Route>`, it renders the specified `component`. For example, <Route path="/about" component={AboutPage} /> will only show `AboutPage` when the URL is `/about`.

The <Link> Component: Navigation Without Reloads

The `<Link>` component provides declarative, accessible navigation. It's the replacement for the traditional `<a>` tag. The key difference is that `<Link>` prevents a full page reload, creating the smooth experience of a Single-Page Application (SPA). You use it like this: <Link to="/about">About Us</Link>.

The <Switch> Component: Exclusive Routing

The `<Switch>` component is used to group `<Route>`s. It's important because it will only render the *first* `<Route>` inside it that matches the current URL. Without it, multiple routes could render at the same time (e.g., a route with `path="/"` would match every URL). This is essential for predictable routing and handling "Not Found" pages. Note: In React Router v6, `<Switch>` is replaced by `<Routes>` with a similar purpose.

The Result: A Seamless SPA Experience

By combining `<Link>`, `<Route>`, and `<Switch>`, you create the full navigation flow of a SPA. A user clicks a `<Link>`, the URL changes without a page refresh, and the `<Switch>` ensures the correct `<Route>` renders its component. This is the foundation of building multi-page experiences in a single-page app.

Practice Zone


Interactive Test 1: Match the Component

Match each React Router component to its primary function.

Arrastra en el orden correspondiente.


Arrastra las opciones:

<Link to="/contact">Contact</Link>
<Switch>...</Switch>
<Route path="/contact" component={Contact} />

Completa el código:

Maps a URL to a component______
Navigates without page reload______
Renders only the first matching route______
Unlock with Premium

Interactive Test 2: Build a Router

Rellena los huecos en cada casilla.

import { Route, Switch, Link } from 'react-router-dom';

function App() {
  return (
    <div>
      <nav>
        < to="/">Home</>
        < to="/profile">Profile</>
      </nav>

      <>
        < path="/profile" component={UserProfile} />
        < path="/" component={HomePage} />
      </>
    </div>
  );
}
Unlock with Premium

Practice Example: Code Editor

Create a component with two routes. The first route, at path `/`, should display an `h1` with "Welcome Home!". The second, at path `/Dashboard`, should display an `h1` with "Admin Dashboard". Wrap them in a Switch.

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

function App() { return ( <Switch> <Route exact path="/"> <h1>Welcome Home!</h1> </Route> <Route path="/Dashboard"> <h1>Admin Dashboard</h1> </Route> </Switch> ); }

Unlock with Premium

Knowledge Check

Why is the <Link> component preferred over a standard <a> tag for internal navigation in a React Router app?


Unlock with Premium

React Router in Action

Once you understand the basics of <Route>, <Link>, and <Switch>, you can build complex navigation structures. Here’s how routing integrates with other common application needs.


1. Dynamic Routes with URL Parameters

Often, you need a route that can handle dynamic data, like a user ID or a blog post slug. You can define a URL parameter with a colon (`:`). React Router will then make this parameter available in your component.

// This route matches /users/1, /users/jane, etc.
<Route path="/users/:userId" component={UserProfile} />

// Inside UserProfile.js
function UserProfile({ match }) {
  return <h2>User ID: {match.params.userId}</h2>;
}

User ID: 123

2. Protected Routes for Authentication

You can create custom route components to protect pages that require a user to be logged in. This "ProtectedRoute" component internally checks for an authentication token and either renders the requested component or redirects the user to the login page.

function ProtectedRoute({ component: Component, ...rest }) {
  const isAuthenticated = checkAuth(); // Your auth logic
  return (
    <Route {...rest} render={(props) => (
      isAuthenticated
        ? <Component {...props} />
        : <Redirect to="/login" />
    )} />
  );
}

// Usage
<ProtectedRoute path="/Dashboard" component={Dashboard} />
Redirecting to /login...

Practical Takeaway: React Router is more than just swapping components. It's a powerful tool for structuring your entire application, managing user access, and creating dynamic, data-driven user experiences.

React Router Glossary

Client-Side Routing
The process of handling URL changes and rendering views directly in the browser using JavaScript, without making a request to the server for a new HTML page. This is the core principle behind Single-Page Applications (SPAs).
React Router
The standard, de-facto library for routing in React. It provides a collection of navigational components to declaratively manage your application's URLs.
`<Route>`
A component whose basic responsibility is to render some UI when its `path` prop matches the current URL.
`<Link>`
A component used to create links for internal navigation. It renders an accessible `<a>` tag but intercepts the click event to prevent a full page reload.
`<Switch>` (v5)
A component that renders the first child `<Route>` or `<Redirect>` that matches the current location. It ensures that only one route is rendered at a time. In v6, this is replaced by `<Routes>`.