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
HomePage
component.You will need to create a
home
directory.src\home\HomePage.js
import 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
keeptrack
and 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-dom@6.3
Yarn
yarn add react-router-dom@6.3
Configure the routes.
src/App.js
import 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.css
header {
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.js
function 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 theto
property 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
Projects
in the navigation. - Verify you are taken to the
/projects
route and theProjectsPage
displays. - Click on
Home
in the navigation. - Verify you are taken to the
/
route and theHomePage
displays.
- Visit the root of the site: