Auteur Haris Spahija Tags Technische blog Datum

I will teach you in a 2 part blog how to create, manage and optimize a React SPA using a Headless Wordpress backend. We will learn how to work with dynamic routing, create meta tags in a React SPA, how to install Wordpress trough Docker, make use of ACF and how to use the Google Search Console. SSR is not needed in order to create a simple but manageable promotion website or blog. 

In this part we will set up our basic Wordpress environment on our local machine using Docker and making use of the integrated Rest API from Wordpress. Next we will learn how to make use of React Router and how to implement  dynamic routing in our React environment. 

Why Wordpress?

Wordpress is super simple to use, its very user friendly, easily to update and has pretty much a lot of work already done for us. A complete CMS from scratch can be very challenging and becomes often very time consuming. Luckily Wordpress can do a lot of the work for us. Since the 4.7 update we can make use of the Wordpress REST API without making any modifications to our Wordpress. The REST API will serve as our backend and will hold and manage the content for our website. 

In addition, tools like ACF (Advanced Custom Fields) can aid us in customizing our posts and pages. This way we can create a completely custom website trough a familiar platform like Wordpress. Tools like Yoast SEO can help us with Search Engine Optimization and managing our indexation for Google's Search Bot. 

Why React SPA?

I have worked for the last 2.5 years with React and seen many implementations of this amazing library. React allows the developer to create completely unique UI's that can enhance the UX of a website tremendously. SPA and SEO usually dont go together quite well, mainly because of Google's Search Engine not being able to render trough most of the Javascript. There are a couple of solutions/tricks that can aid us in achieving a well optimized SPA. 

What is an SPA?

SPA stands for Single Page Application. Unlike other websites and frameworks that have multiple pages, React allows us to never leave a single page. Thats right! You can create a complete website with just one page. React works by manipulating a single div on one page, called the "root" div. Because javascript is so flexible it allows us to create entire webpages without ever leaving the page. This way we can create fluent interfaces that switch between simulated pages without having any downtime. 

In general I think React is a great tool to create a very amazing looking frontend without having to type a ton of repetitive code. 

Note: This guide will show examples using OSX, some terminal commands may be different between operating systems. If you have any questions on how to execute commands on your OS feel free to comment below or contact me!

Installation/Setup

In order to create a Wordpress and React environment we have to install a couple of things. In this tutorial we will create an environment that is local for us. If you would like to host your set up and learn more about DevOps checkout one of our other blogs: https://hybrit.org/blog/angular-in-jenkinsx-and-kubernetes In part 2 I will discuss how we can expose our environment online for SEO!

Wordpress + Docker

Usually Wordpress requires an apache set up that will run the PHP for the Wordpress environment. As a developer we don't want to manually configure everything. A great solution is to use Docker. We can run a local instance of a Docker container that will create our Wordpress environment using compose. 

The Wordpress installation can be different for Mac, Windows and Linux. You can find the docker installation guide here: https://docs.docker.com/install/

Once you have installed Docker on your local machine we can create our new Wordpress site. There should be a basic understanding of how a terminal works in the next parts.
Let's start by creating an empty folder where we will store the docker-compose.yml file.  

mkdir wordpress-backend to create the wordpress-backend folder.

Navigate to the folder and create our docker-compose.yml file.

touch docker-compose.yml

Next up we add the following code to it

These are the default settings for creating a Wordpress environment. Now if you run docker-compose up docker will run in detached mode, pull the required Docker images and start the Wordpress and database containers. You should see something like this: 

Docker compose will host a localhost environment that you can visit at: http://localhost:8000
Here you will be able to run the install of Wordpress. (filling out database might be different per install, you can leave it default for now)
You can set all the install settings in any way you want, they are not important yet. Just make sure to uncheck search engine visibility. We will discuss this in part two of our blog.


Now login to your website using the username and password you set here: http://localhost:8000/wp-login.php
We don’t have to install anything else to access our Rest API since Wordpress 4.7.

In order to test if the API of our Wordpress works you can fire a get request in Postman to http://localhost:8000/?rest_route=/ or just visit the link.

We can check our Hello World post with http://localhost:8000/?rest_route=/wp/v2/pages/2

You should be able to see the example page created by Wordpress.
Let create a couple of pages to simulate a real website.

You can check all the pages available in the REST API with http://localhost:8000/?rest_route=/wp/v2/pages/

Note, you can always change the URL of your REST API using permalinks. In order to do so go to Settings > Permalinks . This will also change the URL of the REST API. 

React + React Router

So now that we have our Wordpress environment set up we can start working on the React part. React works with a Virtual DOM by manipulating the root div on our webpage. This makes it so we will always be on a single page while the application changes/interacts with the user. Thats why React is a SPA. But we don't want to be on one page, we would like to have multiple pages and navigate by changing the URL. This is where React Router will come in. 

React Router will serve as a navigation tool trough our React SPA. It will simulate Routes by adjusting the URL and change the content on the page. Let's start by creating a basic React App. For this we will use NPM and Node. 

Create a new folder ouside the wordpress folder. Here we will create our app. 

npx create-react-app wordpress-frontend

Then navigate to the folder and run it

cd wordpress-frontend && npm start

You should see the base create-react-app landing page.

Next we will need some data before we actually start creating routes. Our routes will be based off the pages that exist in our Wordpress environment. The first step will be to connect our frontend and backend to receive the content for us to display. In order to receive the pages we have to GET the content from Wordpress. We use the library Axios for this. Axios is basically the same as Fetch but has a couple of important added features. Some benefits of Axios:

  • Transformers: allow performing transforms on data before a request is made or after a response is received (We can use this later to only fetch differences instead of everything from Wordpress. This will increase performance) 
  • Interceptors: allow you to alter the request or response entirely (headers as well). Also, perform async operations before a request is made or before Promise settles. (This will be handy for spoofing 404 responses so pages that do not exist do not get indexed.)
  • Built-in XSRF Protection

Our content comes from the headless Wordpress and will determine what pages/links/posts will be available. This will make our entire website async what can be confusing from time to time. Luckily Axios allows us to work with promises what will come to a great benefit to us!

First we add axios to our project with: 

npm install axios

Lets modify our App.js file in the src folder to reach out for the pages and display the page-slugs on our website.

The reason we use a class is to be able to use the constructor and add a pages state. We can then use the array that will be stored in this.state.pages to render our pages dynamically. The reason we use state to store pages is so we are able to store pages in the cookies or local storage of the user. Before we actually fetch the content we can then compare the local storage and our Wordpress environment. We will discuss further optimization in Part 2. 

You can also use React Hooks if you want to, useState also works and you can more about it here: https://reactjs.org/docs/hooks-state

Secondly we will perform a function on  componentDidMount to get all of our pages. getAllPages will fetch the pages from our Wordpress and store them into the state. In the render we will perform a map of our state to render the slugs of our pages. You should see something like this. 

Great! Now we can see that we get some data into our website. Next we will create individual pages so we can visit them with http://localhost:3000/sample-page/

Lets install react-router to create routing for React. npm install react-router-dom

React Router allows us to create individual routes for our pages and adjust our URL. In order to dynamically create the routing we can add the following code. Dont forget to import react-router-dom! Lets change the following code inside the render function to:

Create a folder inside the src folder called components and add ExamplePage.js to it. Inside ExamplePage.js we will add the following code

This code allows us to use the pages from the state to create links and routes. As you can see when you click on one of the links you will be navigated to the right url. 

Let's add some styling to our App like so. 

Voila, here we have a working example of our SPA with React Router trough headless Wordpress. But there are some things missing. We still need to add our blog posts and 404 handling for react router. As you can see the pages will be switched instantly because we are not refreshing any page. This is one of the huge benefits or creating a website like this. 

 

Blogposts

We can do the same thing with our blog posts. Next we create a basic landing that page that will display our latests blogposts in a list. 

Let's start by creating a HomePage component. This will serve both as our landing page and homepage. Inside the components folder we can create a HomePage.js file. It will look something like this

Add styling to App.css

And finally add the getAllPosts function to App.js

We basically do the same thing as we did for the Pages. A good practice is to combine the two fetches into one in order to avoid multiple requests. For sake of simplicity the two functions are split here.
Don’t forget to add the posts object to the state like so

Lets implement our HomePage to the app. First off import the HomePage on App.js

Add HomePage<Link> to the Navbar

And add an extra route for the HomePage. We can also add a redirect to the default route. 

As you can see the link to the homepage is "/" . This is the default route for React Router. We can make sure that the user will be redirected to the HomePage once a Route is not found. We do this by using the <Redirect> component. In order to use multiple routes like this we have to wrap our routes in a <Switch> component. <Switch> basically allows us to "switch" between routes once a route is not found. See it more as a switch case but for our routes. 

Our final App.js should look something like this:

So there we have it, dynamic routing trough Wordpress and React Router.

You can always add more posts/pages if you want without adjusting the React code. If you got stuck somewhere checkout the repository for this blogpost here: https://github.com/HarisSpahija/hybrit-wordpress-frontend

In the next part of this series we will discuss how we can add SEO and meta tags using React Helmet and Google Search Console.
Feel free to comment with questions or contact me at haris.spahija@hybrit.org

I hope you enjoyed this tutorial! See you at part 2!

Haris Spahija
<Code> creator at HybrIT

Deel jouw IT-vraagstuk.

Vul het formulier in en ontvang binnen 2 werkdagen een reactie.

Heb je liever persoonlijk contact? Bel dan naar +31 (0)30 227 31 97.

Wil jij weten wat we met je gegevens uit dit formulier doen? Lees dan onze privacyverklaring.

IT’s easy.
  1. Beschrijf het IT-vraagstuk.
  2. Wij bekijken het IT-vraagstuk en bellen je terug met een voorstel.
  3. Op basis daarvan beslis jij of je een kennismakingsgesprek wilt.