We use cookies to enhance your experience on the site
CodeWorlds

React Router - Fundamentals of Interplanetary Navigation

📚 Note for space travelers: This module contains extensive material about routing and navigation in React. Due to the complexity of the topic, the material has been divided into many sections. You don't have to absorb everything at once - you can return to individual parts at any time during your cosmic educational journey. Think of this module as a detailed galactic atlas - you can explore it piece by piece.

On our cosmic journey through the world of React, we now visit the interplanetary navigation system - React Router. Just as astronauts need a navigation system to move between planets, React applications need routing to allow users to move between different views of the application.

What is React Router?

React Router is the standard library for handling routing in React applications. It allows for:

  • Rendering different components depending on the URL
  • Synchronizing the UI with the URL address
  • Navigation without page reloading (Single Page Application)
  • Easy passing of parameters through the URL
  • Nesting and grouping of paths

Imagine that you're creating a navigation system for a space fleet, where each planet (page) has its unique identifier (URL), and the spaceship (user) can freely travel between them without having to launch from Earth each time (reloading the entire application).

Installing React Router

Before we embark on our cosmic journey, we need to install the appropriate navigation systems. For web applications, we use

react-router-dom
:

1# Installation using npm
2npm install react-router-dom
3
4# Installation using yarn
5yarn add react-router-dom
6
7# Installation using pnpm
8pnpm add react-router-dom

Basic React Router Components

React Router offers key components that work like parts of an interplanetary navigation system:

1. BrowserRouter

BrowserRouter
is the main component that wraps the entire application and uses the HTML5 History API to synchronize the UI with the URL. It's like the mission control center:

1import { BrowserRouter } from 'react-router-dom';
2
3function App() {
4  return (
5    <BrowserRouter>
6      {/* Place Routes and Route components here */}
7    </BrowserRouter>
8  );
9}

2. Routes and Route

Routes
and
Route
allow you to define which components should be rendered for specific URL paths:

1import { BrowserRouter, Routes, Route } from 'react-router-dom';
2
3function App() {
4  return (
5    <BrowserRouter>
6      <Routes>
7        <Route path="/" element={<Home />} />
8        <Route path="/mars" element={<MarsBase />} />
9        <Route path="/jupiter" element={<JupiterStation />} />
10        <Route path="/neptune" element={<NeptuneColony />} />
11      </Routes>
12    </BrowserRouter>
13  );
14}

In the example above:

  • Route
    "/"
    leads to Earth (component
    Home
    )
  • Route
    "/mars"
    leads to the Mars base (component
    MarsBase
    )
  • Route
    "/jupiter"
    leads to the Jupiter station (component
    JupiterStation
    )
  • Route
    "/neptune"
    leads to the Neptune colony (component
    NeptuneColony
    )

3. Link

The

Link
component is used for navigation between paths without reloading the page. It works like an interplanetary teleporter:

1import { Link } from 'react-router-dom';
2
3function Navigation() {
4  return (
5    <nav>
6      <ul>
7        <li><Link to="/">Earth (Home)</Link></li>
8        <li><Link to="/mars">Mars Base</Link></li>
9        <li><Link to="/jupiter">Jupiter Station</Link></li>
10        <li><Link to="/neptune">Neptune Colony</Link></li>
11      </ul>
12    </nav>
13  );
14}

4. NavLink

NavLink
is a special version of the
Link
component that adds an
active
CSS class when the current URL matches the link's path. It works like a map with the current location highlighted:

1import { NavLink } from 'react-router-dom';
2
3function Navigation() {
4  return (
5    <nav>
6      <ul>
7        <li>
8          <NavLink
9            to="/"
10            className={({ isActive }) => isActive ? "planet-active" : ""}
11          >
12            Earth (Home)
13          </NavLink>
14        </li>
15        <li>
16          <NavLink
17            to="/mars"
18            className={({ isActive }) => isActive ? "planet-active" : ""}
19          >
20            Mars Base
21          </NavLink>
22        </li>
23        {/* Other links */}
24      </ul>
25    </nav>
26  );
27}

Simple Example of a Complete Application with React Router

Below is a simple example of a space application with routing:

1import React from 'react';
2import { BrowserRouter, Routes, Route, Link, NavLink } from 'react-router-dom';
3
4// Components for individual "planets"
5function Home() {
6  return <h1>Welcome to Earth! Space Mission Control Center</h1>;
7}
8
9function MarsBase() {
10  return <h1>Mars Base: The Red Planet awaits exploration</h1>;
11}
12
13function JupiterStation() {
14  return <h1>Jupiter Station: Observing the largest planet in the system</h1>;
15}
16
17function NotFound() {
18  return <h1>Lost in space! This path does not exist.</h1>;
19}
20
21// Navigation component
22function SpaceNavigation() {
23  // Styles for the active "planet"
24  const navLinkStyles = ({ isActive }) => ({
25    fontWeight: isActive ? 'bold' : 'normal',
26    textDecoration: isActive ? 'underline' : 'none',
27    color: isActive ? '#ff4500' : '#fff',
28  });
29
30  return (
31    <nav style={{ background: '#1a1a2e', padding: '1rem' }}>
32      <ul style={{ display: 'flex', listStyle: 'none', gap: '1rem' }}>
33        <li>
34          <NavLink to="/" style={navLinkStyles}>
35            Earth
36          </NavLink>
37        </li>
38        <li>
39          <NavLink to="/mars" style={navLinkStyles}>
40            Mars
41          </NavLink>
42        </li>
43        <li>
44          <NavLink to="/jupiter" style={navLinkStyles}>
45            Jupiter
46          </NavLink>
47        </li>
48      </ul>
49    </nav>
50  );
51}
52
53// Main application
54function App() {
55  return (
56    <BrowserRouter>
57      <div style={{ fontFamily: 'Arial', maxWidth: '800px', margin: '0 auto' }}>
58        <h1>Interplanetary Navigation System</h1>
59
60        <SpaceNavigation />
61
62        <div style={{ padding: '2rem', background: '#0a0a1a', color: 'white' }}>
63          <Routes>
64            <Route path="/" element={<Home />} />
65            <Route path="/mars" element={<MarsBase />} />
66            <Route path="/jupiter" element={<JupiterStation />} />
67            <Route path="*" element={<NotFound />} />
68          </Routes>
69        </div>
70      </div>
71    </BrowserRouter>
72  );
73}
74
75export default App;

Pay attention to a few key elements:

  1. BrowserRouter
    wraps the entire application
  2. Routes
    groups all available paths
  3. The
    SpaceNavigation
    component uses
    NavLink
    to highlight the current location
  4. The special path
    "*"
    (asterisk) handles all non-existent URLs

Code Organization in Larger Applications

In larger space applications, it's good practice to organize routing components in a more modular way:

1// src/routes/AppRoutes.js
2import { Routes, Route } from 'react-router-dom';
3import Home from '../pages/Home';
4import MarsBase from '../pages/MarsBase';
5import JupiterStation from '../pages/JupiterStation';
6import NotFound from '../pages/NotFound';
7
8function AppRoutes() {
9  return (
10    <Routes>
11      <Route path="/" element={<Home />} />
12      <Route path="/mars" element={<MarsBase />} />
13      <Route path="/jupiter" element={<JupiterStation />} />
14      <Route path="*" element={<NotFound />} />
15    </Routes>
16  );
17}
18
19export default AppRoutes;
20
21// src/App.js
22import { BrowserRouter } from 'react-router-dom';
23import AppRoutes from './routes/AppRoutes';
24import SpaceNavigation from './components/SpaceNavigation';
25
26function App() {
27  return (
28    <BrowserRouter>
29      <div className="space-app">
30        <SpaceNavigation />
31        <main>
32          <AppRoutes />
33        </main>
34      </div>
35    </BrowserRouter>
36  );
37}

Benefits of Using React Router

  1. Unified user experience - navigation without page reloading creates a sense of fluidity
  2. Better UX - faster transitions between screens, state preservation
  3. Better code organization - clear application structure based on paths
  4. Easier testing - ability to test components for specific paths in isolation
  5. SEO - possibility of optimization for search engines (especially with SSR/SSG)

Summary

React Router is a key element in building modern React applications. It enables organized navigation between different parts of the application and creates an intuitive structure for users.

In our cosmic metaphor, React Router works like an interplanetary navigation system - it allows the user (spaceship) to freely move between different planets (components/views), without having to return to Earth (reload the entire application) on each journey.

In the following modules, you'll learn how to use more advanced React Router features, such as URL parameters, nested routing, and route protection.

Go to CodeWorlds