Lab 21: Route Parameters
Objectives
- Navigate to a route with a parameter
Steps
Navigate to a route with a parameter
Add a
find
method toprojectAPI
to return a singleProject
byid
src\projects\projectAPI.ts
const projectAPI = {...+ find(id) {+ return fetch(`${url}/${id}`)+ .then(checkStatus)+ .then(parseJSON);+ },+...};Copy the files
snip-master\labs\js\snippets\lab21\ProjectPage.tsx and ProjectDetail.tsx]
into thesrc\projects
directory.These files contain some pre-built components we will use in this lab. Take a moment to review the code in them.
Add a route to display the
ProjectPage
(notice that we now have aProjectPage
and aProjectsPage
so be careful you are in the correct file).src\App.tsx
import ProjectsPage from './projects/ProjectsPage';+ import ProjectPage from './projects/ProjectPage';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"><Routes><Route path="/" component={HomePage} /><Route path="/projects" component={ProjectsPage} />+ <Route path="/projects/:id" element={<ProjectPage />} /></Routes></div></Router>);}Make the name and description clickable by adding a
<Link />
component around them.src\projects\ProjectCard.tsx
+ import { Link } from 'react-router-dom';...<section className="section dark">+ <Link to={'/projects/' + project.id}><h5 className="strong"><strong>{project.name}</strong></h5><p>{formatDescription(project.description)}</p><p>Budget : {project.budget.toLocaleString()}</p>+ </Link><buttontype="button"className=" bordered"onClick={() => {handleEditClick(project);}}><span className="icon-edit "></span>Edit</button></section>...Verify the new route works 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 the name or description in any of the project cards .
- Verify you are taken to the
/projects/1
route and theProjectPage
displays theProjectDetail
component.
<
- Visit the root of the site: