Lab 20: Router Basics
Objectives
- Create another Page (container component)
- Add Basic Routes (install, configure)
- Create a Navigation Menu
Steps
Create another Page (container component)
Create a
HomePagecomponent.You will need to create a
homedirectory.src\home\HomePage.tsximport React from "react";function HomePage() {return <h2>Home</h2>;}export default HomePage;
Add Basic Routes (install, configure)
Open a
command prompt(Windows) orterminal(Mac).Change the current directory to
code\keeptrack.If the top level directory you have open in VS Code is
keeptrackand you are using the integrated terminal you will already be in this directory.Run one of the following commands to install
React Router:npm
npm install react-router-domYarn
yarn add react-router-domConfigure the routes.
src/App.tsximport React from 'react';import './App.css';import ProjectsPage from './projects/ProjectsPage';+ import { BrowserRouter as Router, Routes, Route, NavLink} from 'react-router-dom';+ import HomePage from './home/HomePage';function App() {- return (- <div className="container">- <ProjectsPage />- </div>- );+ return (+ <Router>+ <div className="container">+ <Routes>+ <Route path="/" element={<HomePage />} />+ <Route path="/projects" element={<ProjectsPage />} />+ </Routes>+ </div>+ </Router>+ );};export default App;
Create a Navigation Menu
Modify your CSS styles to include some customizations for the navigation menu.
src/App.cssheader {height: 5.1875rem;}a.button.active {border: 1px solid var(--fore-color);}...Add two
<NavLink>components (which are provided by the React Router) and set them to visit the configured routes.src/app.tsxfunction App() {return (<Router>+ <header className="sticky">+ <span className="logo">+ <img src="/assets/logo-3.svg" alt="logo" width="49" height="99" />+ </span>+ <NavLink to="/" className="button rounded">+ <span className="icon-home"></span>+ Home+ </NavLink>+ <NavLink to="/projects" className="button rounded">+ Projects+ </NavLink>+ </header><div className="container">...</div></Router>);};...You can make any
<a>tag a<NavLink>and add thetoproperty to set thehref.Verify the routes are working by the following these steps:
- Visit the root of the site:
http://localhost:3000/and refresh the page in your browser. - Click on
Projectsin the navigation. - Verify you are taken to the
/projectsroute and theProjectsPagedisplays.
- Click on
Homein the navigation. - Verify you are taken to the
/route and theHomePagedisplays.
- Visit the root of the site: