CalvinTorra
Connect your WordPress API To React Using Hooks
IdontKnowJS

Grab The Guides

Grab The Ultimate Guide To Headless Wordpess and Next.js

Save time with your Jamstack Headless WordPress and Next.js integration. The guide I wish I had when first starting out Here


So I read this tweet that sent me into a rabbit hole of investigation that turned up nothing.

Turns out I was looking in all the wrong places, such is life.

Apparently it’s now possible to use WordPress as a headless CMS while using whatever frontend solution you like.

Well this apparently isn’t so new. It’s been around for a while and I believe it would be classed as a JamStack……Stacks of Jam.


So I love WordPress, it was my go-to solution for entering the industry as a Web designer, it gave me the opportunity to go freelance many moons ago and things went well.

However, what I didn’t do was learn PHP which would have given me full access to the full potential that WordPress had to offer!

More recently I settled on adding Javascript to my utility belt and finding out that I can now use WordPress as well as Javascript on the frontend was the nail in the coffin!

What’s the point?

👍🏽
The most interesting thing for me while learning React was the ability to map over an API and easily display the date while passing this info into a component.

So I build the component (a blog post card) once, then map over the api data of posts that I have saved within WordPress and repeat those cards for every post I have.

👍🏽
I am already paying about €200 a year for my WordPress hosting with Siteground. I did this because my host of 10 years Hostgator was painfully slow and my client sites were slowing down.

So I might as well utilise the WordPress ecosystem that I’m paying for and mix it with what I’m now using.

👍🏽
I’m able to use WordPress as a CMS, which I’m already used to (muscle memory) and automatically update my React frontend without editing any code.

I just hit publish on my WordPress post and the React app will render that post on it’s next refresh for the end-user.

👍🏽
If you have an app to accompany your website / brand, you can also use WordPress as your source of truth for content. Both you frontend framework and your app can pull content from the same place and you only need to update the info in one place.

👍🏽
I wanted to keep all of my images and content in a robust system designed for that purpose. I’m hosting my React apps on Firebase and I’m concerned that overloading that with files and images would bring me a surprise bill at the end of the quarter with no warning.

Frontity

I came across a bunch of Youtube videos that promised to explain how to create this Stack of Jam and Frontity popped up as the fully integrated solution.

Long story short, it just didn’t suit my way of working. After downloading the framework and committing a complete day to go through the documentation, I imagined there must be a faster way to do this in a repeatable format.

WordPress API and React Hooks

More research brought me to the WordPress API which for me was really quite beautiful.

If you have a wordpress installation it should already be active
http://yourwebsitehere.com/wp-json/wp/v2/?_embed

With the correct URL suffix you’ll be able to access your pages, posts, authors etc etc.

So here goes a quick and dirty explanation on how to get yours going.

The WordPress Set Up

To set this up I decided to go with Custom Post Types. I’d explain why but I’ve already forgotten.

However these custom post types give you a lot of flexibility to add additional fields that you wouldn’t have inside the normal post section of wordpress.

You can add image upload boxes, additional text boxes.

I kept mine super simple for now, I added another featured image box so that when I’m hunting for the code in the API I only have to look in one place for everything that I’ve personally added.

Adding Custom Post Types

The three plugins that I needed were

Cusotm Post Type UI – To create custom post types

Advanced Custom Fields – To create and display custom fields

ACF To Rest API – This exposes your custom fields to the API.

So you follow the instructions to create a Custom Post Type, you then use Custom fields to add your new additional fields and then visit your API link where ACF to Rest has added these new fields to the API for you.

My custom posts type I have named React Posts.

Notice that it’s separate to my normal WordPress posts. This means that we’ll need to figure out where inside the API these new posts live.

Luckily for me, it was quite easy.

My WordPress API is
http://calvinsfakesite.com/wp-json/wp/v2/?_embed

Which means my custom posts live here
http://calvinsfakesite.com/wp-json/wp/v2/react_blog?_embed

So find your link and you’ll be presented with a bunch of code that will make no sense.

To prettify your API data, install JSON formatter chrome extension. This will take your API info and format it into a nice and easy to read structure.

Trust me, this will make your life a lot easier when hunting for data.

Fetching WordPress API in React

So now you have your API link
http://calvinsfakesite.com/wp-json/wp/v2/react_blog?_embed
we can now pull it into React.

It looks like a lot but it’s ok, it’s not that bad.

I’m using Context from React to create a global state that any component can have access to.

I’m also importing useState and useEffect.

Creating a context called “WordPressContext”.

Using a React Hook to create an empty array called “posts” and “setPosts” is called when I want to put data into “posts”.

“siteURL” is my WordPress API link. Replace it with yours.

useEffect is similar to componentDidMount if I remember correctly and loads as soon as we load the app.

Inside useEffect, we’re making a call to the API and if WordPress answers the phone call, it will give us the posts we’re asking for.

We can then send those posts back up to the top of the screen using “setPosts” with the data we got on the call with Worpdress.

I usually Console log the hook at the end just to see if the data we got from the call is what I was expecting.

Right at the end we’re creating a context provider and passing the data from the “posts” hook into it as the value.

Then we’re exporting that provider by default.

I can now wrap my entire app with the provider I just exported and give every component access to the posts.

Now is this the best way to get things done?

Probably not, I think in an ideal world I should keep the data for my blog posts as close to the components that need it as possible.

So maybe I should fetch that data from WordPress inside a blog roll component only.

These are considerations that I’ll take into account if and when this website grows, but some something small like my website, I’m not too worried about performance.

The amount of data going coming in is minimal and so shouldn’t be a cause for concern. If I were building a large scalable app, I’d need to rethink and refactor where I choose to pull data in and when.

Rendering The Data

Now the blog roll, which is a page that displays ALL blog posts, will take the data from the provider I just created.

Below I’ve deleted a lot of code in between the two important parts that I wanted to show you.

We import all the usual things including the { WordPressContext }, then within the component, we’re destructuring the context object and pulling off the posts so that we can use them.

We’re then mapping over all the posts and sending each one into a card component for display purposes.

I’m using the … spread operator to send every bit of info from each post into the card so I can use whatever gets sent from WordPress.

With the map function we’re telling React to make a card for each post that we received on the call with WordPress.

If there’s 1 post, just do this once. If there’s 10 posts, make 10 cards.

I’m also using the post.id as the key so React can tell which is which if it needs to update any of them later.

Inside The Card Component

So you remember above I used the … spread operator to send all the info to the card? Well we now have access to that as props inside the card.

Here’s a stripped-down example of how we render it with some twists included.

If you console log the props, you’ll see we have access to the title of the post, however, we need to include the props.title.rendered on the for it to display.

Take note also that rendering the actual post itself and the excerpt needs to be done via dangerouslySetInnerHTML, which tripped me up at first.

We also have access to the slug of the post URL, which will allow us to use React Router to create links to the post within our app.

Here’s an example of how the Route is set up
This allows me to dynamically create “pages” for the articles to live.

Here’s how the post looks as an object

Here’s an example of the dynamically created Link
So inside the card, we’re creating a button using the URL slug.

Here’s an example of the blog post page
Once you’ve created a button and a link, you’ll need a component to render the post based on that link.

This is what the code below does. It looks at the URL that you just clicked on, compares that slug to the list of slugs we have been sent from WordPress, filters and matches that post and renders it.

Wrapping Up

That’s basically all I needed to know to get all of my content from my WordPress back end and display it on the frontend with React.

A “Stack of Jam

Yes I could show every single file and how I set it up etc but this post is long enough.

As long as we know
– How to set up WordPress
– Retrieve that data
– Mapping over the data
– Displaying it
– Creating links to individual posts
– Then displaying it again, the cycle repeats.

You have an unlimited number of ways to manipulate that content. I’m looking forward to finding new ways to use this method of working.

Grab The Guides

React Query
Redux Toolkit
React Testing Library
Contact Me