In the last two articles we have shown how to get the articles, display them and also use the React Router for pagination. In this tutorial we will now see how to show a single article using the React Router in out Headless WodPress application.
How are we going to do this?
- We will get the Slug from the Route
- Check if there is an article with that slug
- If not, fetch a new one
- If we still don’t have an article, show 404 Page Not Found
- If found, show the article
Since we will always try to fetch a new article if we don’t have such slug, we will store not found slugs in state so we don’t end up in an infinite loop.
App.js and add the new React hook
Fetching Articles by Slug
We need a method to fetch new articles by slug, so let’s create a method for that. Add this method inside of the
If we find an article, we will merge that data with other articles so we can find it next time. If not, we will store that slug in our state to
Showing Article by Slug
Let’s now create a method to get an article by the provided slug. This will be a component that we will set for our Route.
We get the
id which will be our slug form the React Router
params and then we are trying to find if we have one. If we don’t find one and if there are no such slugs inside of our state for
notFoundSlugs, then we try to fetch one.
After that, we move the
article object into the
Not Found Page Component
This is a simple component that will display that there are no data for that URL.
The Article Component
In the last tutorial, we have created a dummy component just to hold some data. Now, we will update that component that will show the
NotFoundPage component or the article information.
Updating the Single Article Route
We will now have to replace the
<Article /> component inside of the single route with our new method to find an article by slug
This is the route:
<Route path="/:id"> <GetArticleBySlug /> </Route>
Here is the whole code example combined together. Once you unzip it, make sure to run
npm install inside of that folder to install everything you need it to run.
With a few more components, you can define the whole app to display single articles or 404 pages. Using the React Router and state, it is even easier to display such data.
How have you handled 404 and single pages with React?Become a Sponsor