useParams is a React Router hook that returns an object containing values matched by parameter names in the current route path. section 10.1.3
Selecting a bookable from the URL
With a route such as /:id, call const {id} = useParams(). Because parameters are strings, parse the ID before comparing it with numeric data: bookables.find(b => b.id === parseInt(id, 10)). section 10.1.3 section 10.4
Use the hook to:
- Read multiple parameters by destructuring the returned object, such as flavor and size from /milkshake/:flavor/:size. section 10.1.3
- Drive route-specific rendering and data selection, while providing a fallback when the requested bookable is unavailable. section 10.1.3
Listing 10.3 BookablesView accessing ID from the URL
import {Link, useParams} from "react-router-dom"; #1
import {FaPlus} from "react-icons/fa";
import useFetch from "../../utils/useFetch"; #2
import BookablesList from "./BookablesList";
import BookableDetails from "./BookableDetails";
import PageSpinner from "../UI/PageSpinner";
export default function BookablesView () {
const {data: bookables = [], status, error} = useFetch( #3
"http://localhost:3001/bookables"
);
const {id} = useParams(); #4
const bookable = bookables.find(
b => b.id === parseInt(id, 10) #5
) || bookables[0];
if (status === "error") {
return <p>{error.message}</p>
}
if (status === "loading") {
return <PageSpinner/>
}
return (
<main className="bookables-page">
<div>
<BookablesList
bookable={bookable}
bookables={bookables}
getUrl={id => `/bookables/${id}`} #6
/>
<p className="controls">
<Link #7
to="/bookables/new"
replace={true}
className="btn">
<FaPlus/>
<span>New</span>
</Link>
</p>
</div>
<BookableDetails bookable={bookable}/>
</main>
);
}
#1 Import the useParams hook.
#2 Import our useFetch custom hook.
#3 Retrieve the bookables with useFetch.
#4 Assign the ID parameter value to a local variable.
#5 Use the ID to get the specified bookable.
#6 Provide a function to generate URLs for bookables.
#7 Include a link to the form for creating new bookables.
Inspect the focused BookablesView listing showing imports, useParams, numeric conversion, loading states, and rendered child components. section 10.1.3
