- Create another Page (container component)
- Add Basic Routes (install, configure)
- Create a Navigation Menu
-
Create a
HomePage
component.You will need to create a
home
directory.import React from 'react'; function HomePage() { return <h2>Home</h2>; } export default HomePage;
-
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 install react-router-dom @types/react-router-dom
yarn add react-router-dom @types/react-router-dom
-
Configure the routes.
import React from 'react'; import './App.css'; import ProjectsPage from './projects/ProjectsPage'; + import { BrowserRouter as Router, Route, NavLink, Switch } from 'react-router-dom'; + import HomePage from './home/HomePage'; function App() { - return ( - <div className="container"> - <ProjectsPage /> - </div> - ); + return ( + <Router> + <div className="container"> + <Switch> + <Route path="/" exact component={HomePage} /> + <Route path="/projects" exact component={ProjectsPage} /> + </Switch> + </div> + </Router> + ); }; export default App;
-
Modify your CSS styles to include some customizations for the navigation menu.
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.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="/" exact className="button rounded"> + <span className="icon-home"></span> + Home + </NavLink> + <NavLink to="/projects/" className="button rounded"> + Projects + </NavLink> + </header> <div className="container"> <Switch> <Route path="/" exact component={HomePage} /> <Route path="/projects" exact component={ProjectsPage} /> </Switch> </div> </Router> ); };
You can make any
<a>
tag a<NavLink>
and add theto
property to set thehref
.You need exact in both home NavLink and Route.
exact
in theNavLink
keeps Home and Projects from being active(highlighted at the same time)exact
in the Route keeps/projects
from showing Home and the projects list when going to projects route (it shows both without Switch)
-
Verify the routes are working by the following these steps: