📚 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.
React Router is the standard library for handling routing in React applications. It allows for:
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).
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-domReact Router offers key components that work like parts of an interplanetary navigation system:
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}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:
"/" leads to Earth (component Home)"/mars" leads to the Mars base (component MarsBase)"/jupiter" leads to the Jupiter station (component JupiterStation)"/neptune" leads to the Neptune colony (component NeptuneColony)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}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}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:
BrowserRouter wraps the entire applicationRoutes groups all available pathsSpaceNavigation component uses NavLink to highlight the current location"*" (asterisk) handles all non-existent URLsIn 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}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.