Creating a new route and using the Param Hook
Now that we have React Router set up successfully, we can start creating a new route for viewing a single post. This route will look as follows: /post/:id, with :id being a URL param containing the id of a post to be viewed.
A URL param is a parameter used in an URL to define dynamic content. For example, in the /post/:id route, the /post/ part would be a static string, but the :id will be replaced with a dynamic post ID. Let’s assume you have an URL that ends with /post/8, that would mean that the route matches with the id param being set to 8.
Let’s get started setting up the page and route:
- Copy the
Chapter08_1folder to a newChapter08_2folder by executing the following command:$ cp -R Chapter08_1 Chapter08_2 - Open the new
Chapter08_2folder in VS Code. - Edit
src/api.jsand define a new function to fetch a single post:export async function fetchPost({ id }) { ...