React Router v6

Learning Goals:

  • Understand and articulate the need for routing
  • Be able to confidently implement React Router in a project
  • Utilize URL params to build dynamic routes

Vocab

  • BrowserRouter A <Router> that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL
  • Router is a component provided by React Router.This component is responsible for keeping track of the current location (the URL) and re-rendering your app whenever that location changes.And is shared by all router components (like <BrowserRouter>).
  • Link Links provide declarative, accessible navigation around your application
  • NavLink A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL.
  • Route Its most basic responsibility is to render some UI when a location matches the route’s path
  • Routes A component that wraps your Route components that selects the best path match
  • useParams A hook that allows us to gain access to a Route’s params

Why Routing?

Routing refers to keeping a webpage up to date with the current url, and vice-versa.

Most of the apps you’ve written so far have been single-page applications. One HTML page whose content is updated through user interactions and JS. These DO NOT use routing. They work fine, but put some limits on the user experience of our applications.

If you have written a multi-page application, you may have wrestled with Webpack configs in order to get all your pages built successfully. Fortunately, routing with React is easy! We just need to use a library called React Router.

React Router allows us to conditionally render components based on the current url.

Rather than tell you about how Router works, we’ll work through a series of exercises and examples. We’ll be using this repo to solve a series of challenges listed below.

Installation Instructions

0. Clone repo & review codebase

git clone https://github.com/turingschool-examples/react-router-v6
cd react-router-v6
npm i
npm start

The App is not fully put together. It has a series of components that will serve as building blocks of the final component. You won’t be building out new components, but you will be editing existing ones. Get oriented with the application. Check out all the components. Make some written notes about what you think each is doing.

Installing Router

1. The first step is installing react router

npm install react-router-dom

2. Once you have React Router installed, import your chosen Router

To use React Router, we need to wrap any components that will use a React Router-provided-component in some kind of Router component. We’ll use a Browser Router, since our app will be used in the browser. This Router provides access to the HTML5 History API. But we won’t worry about those details just yet.

// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './Components/App/App';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
<BrowserRouter>
  <React.StrictMode>
    <App />
  </React.StrictMode>
  </BrowserRouter>
);


Rendering the Home component

3. Now, let’s tell React Router what to render at the base URL (‘/’)

// App.js

import './App.css';
import { Routes, Route } from 'react-router-dom';
import Home from '../Home/Home';

function App() {
  return (
    <main className="App">
      <nav>
        <a href="/puppies" className="nav">Puppies</a>
        <a href="/sharks" className="nav">Sharks</a>
      </nav>
      <h1>Puppies or Sharks?</h1>
      <Routes>
        <Route path="/" element={<Home />}/>
      </Routes>
    </main>
  );
}

export default App;

Let’s explore

  1. What happens if you remove the line that starts with import { Routes...? What does the error message say?
  2. What happens if you remove the Routes component? What does the error message say?

We picked / for the path in the route because it designates that there won’t be anything after the URL’s domain name. This represents the base URL.


Rendering Puppies

Your goal is click on the word Puppies and see a grid of 9 puppies on the DOM. The page should look something like the picture on the lesson plan. While you may change components as needed, you shouldn’t outright delete content from the page to achieve this.

Take 10 minutes in pairs to get the puppies rendering

Hints:

  • Use the Creatures component. Formatting and styling is handled for you.
  • What additional react-router components should you use? Do any current components need to change?
  • How do you pass props into a component rendered by a <Route /> ?


Rendering the Sharks


Dynamic Routing

In this exercise, we’ll explore two ways to achieve dynamic routing in order to obtain an animal and its ID from the route: first, we’ll use the Outlet, and then we’ll show you how to implement a dynamic route without using an outlet.


Rendering the CreatureDetails component


Self-Guided Exploration: Outlet

An Outlet is a special component used for rendering child routes in nested routing setups. It acts as a placeholder where the content of child routes will be displayed. The Outlet component specifies where child route components will be rendered within a parent route’s component.

Why Use the Outlet ?
The Outlet component serves as a placeholder for rendering nested route content within a parent component. It’s a fundamental tool that allows you to seamlessly integrate child components’ content into a parent’s layout while maintaining UI coherence.

Real-World Analogy: Twitter Inbox
Imagine a scenario similar to the Twitter inbox. When you access your inbox, you see a list of message previews on the left side of the screen, but the right side remains blank until you select a specific conversation. This structure is where the Outlet comes into play.

Final Reflections

  1. Why use Router?
  2. Describe the following:
    • Route
    • Routes
    • Link
    • NavLink
    • useParams
    • Outlet

Extra Resources:

Lesson Search Results

Showing top 10 results