Introduction and Lesson Plan

Hey there, coding enthusiasts! Today, we're delving into the exciting world of single-page applications (SPAs), with a key focus on navigation. If you're wondering what an SPA is, think of Facebook. When you navigate from your news feed to your profile or to your messages, the entire page doesn't refresh, only certain parts do. Traditional browser navigation doesn't quite apply here. That's when we whip out our secret weapon: the React Router, the Narnia's wardrobe of SPAs.

Route Creation and Usage

Inside every React Router app, there's a key BrowserRouter component. This key component essentially keeps the user interface in sync with the URL on the browser.

Routes are managed using a Routes component that contains Route components for each path in our application. The Route component matches the current location with its path prop and generates the corresponding UI. For instance, the root of the app renders the HomePage and "/about" renders the AboutPage.

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';

function AppRouter() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />}/>
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
}

export default AppRouter;

When we write BrowserRouter as Router, we're essentially saying, "import the BrowserRouter component from the React Router library and refer to it as Router in our code". It's just renaming BrowserRouter to Router.

Linking Between Pages

Navigation between routes is akin to teleportation, made possible using the Link component. Rather than enduring clunky page refreshes, Link smoothly alters the URL by manipulating the browser history, a superpower we indeed need for SPAs!

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';

function AppRouter() {
  return (
    <Router>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
      </Routes>
    </Router>
  );
}

export default AppRouter;

The <nav> tag in HTML is used to define a section of a web page that contains navigation links. Here we define two links using the Link component from React Router, which allow us to navigate between the Home and About pages of our web application.

When a user clicks <Link to="/">Home</Link>, React searches the Routes for one with path="/" . <Route path="/" element={<HomePage />} /> matches the path, so React renders the <HomePage> component.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal