coiai Logo

This article is an English translation of the original Japanese post. Read the Japanese original →

Turning WordPress into a Headless CMS with a React Frontend via the REST API

August 15, 2023

Categories: 未分類

Building a custom WordPress theme felt like a lot of effort for what you actually get, so I decided to turn it into a headless CMS instead.

I'll skip styling for now and just walk through the functionality. Here's what it looks like in action.

Trying a GET request against WordPress posts

Let's try running the following command in Terminal.

curl -X GET "<https://your-wordpress-site.com/wp-json/wp/v2/posts>"

JSON is hard to read in Terminal, so I'd recommend using Postman instead.

Creating the React app

Open Terminal, move into whatever directory you like, and run the following command.

$ npx create-react-app my-ts-headless-cms-app --template typescript

Building the post list page

Create PostList.tsx inside the src directory.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

interface Post {
  id: number;
  title: { rendered: string };
}

const PostList: React.FC = () => {
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    axios.get('https://your-wordpress-site.com/wp-json/wp/v2/posts')
      .then(response => {
        setPosts(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>WordPress Post List</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title.rendered}</li>
        ))}
      </ul>
    </div>
  );
};

export default PostList;

Now open App.tsx and rewrite it.

import React from 'react';
import './App.css';
import PostList from './PostList';

function App() {
  return (
    <div className="App">
      <PostList />
    </div>
  );
}

export default App;

Let's check that this works so far! Open Terminal and run:

$ npm start

Did it start up okay?

If so, let's move on to building the detail page!

Building the detail page

Install axios.

$ npm i axis

Create PostDetail.tsx inside the src directory.

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';

interface Post {
  id: number;
  title: { rendered: string };
  content: { rendered: string };
}

const PostDetail: React.FC = () => {
  const { postId } = useParams<{ postId: string }>();
  const [post, setPost] = useState<Post | null>(null);

  useEffect(() => {
    axios.get(`https://your-wordpress-site.com/wp-json/wp/v2/posts/${postId}`)
      .then(response => {
        setPost(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, [postId]);

  if (!post) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{post.title.rendered}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
    </div>
  );
};

export default PostDetail;

Let's install react-router-dom!

$ nom install react-router-dom

Rewrite App.tsx.

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';

import PostList from './PostList';
import PostDetail from './PostDetail';
import './App.css';

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <div className="Contents">
            <Route index path="/" element={<PostList/>} />
            <Route index path="/post/:postId" element={<PostDetail/>} />
        </div>
      </div>
    </BrowserRouter>
  );
}

export default App;

Wiring up navigation from the list to the detail page

Rewrite PostList.tsx as follows.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

interface Post {
  id: number;
  title: { rendered: string };
}

const PostList: React.FC = () => {
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    axios.get('https://your-wordpress-site.com/wp-json/wp/v2/posts')
      .then(response => {
        setPosts(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>WordPress Post List</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            {/* 詳細ページへのリンク */}
            <Link to={`/post/${post.id}`}>{post.title.rendered}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default PostList;
Turning WordPress into a Headless CMS with a React Frontend via the REST API | coiai Inc.