How to Integrate Your WordPress Blog into a React App


Using the WordPress REST API for Dynamic Content

Want to display your WordPress blog inside a React app? In this guide, I’ll show you how I did it using React components and the WordPress REST API.

In fact, this post is part of my WordPress blog, which I’ve already integrated into my React website. By the end of this, you’ll know how to do the same—merging your WordPress content with React’s framework.

Prerequisites

You’ll need:

  • A WordPress blog (with the REST API enabled by default).
  • Basic knowledge of React and JavaScript.
  • A React app where you want to show your blog.
Step 1: Fetching WordPress Data

WordPress provides an API that returns your blog posts in JSON format. I’ve created a GetData.jsx component to handle fetching this data:

// GetData.jsx
import { useEffect, useState } from 'react';

const GetData = (url) => {
    const [data, setData] = useState([]);

    useEffect(() => {
        fetch(url)
            .then((response) => response.json())
            .then((data) => setData(data))
            .catch((error) => console.error('Error fetching data:', error));
    }, [url]);

    return data;
};

export default GetData;

Code language: JavaScript (javascript)

This component uses React’s useState and useEffect hooks to fetch and store data from a URL (your WordPress API endpoint). When the component mounts, fetch() is called to retrieve posts, and the response is stored in the component’s state.

Step 2: Displaying the Blog Posts

Now that the data is being fetched, we need to display the blog posts.

// Blog.jsx
import React from 'react';
import GetData from './GetData';
import PostDetail from './PostDetail';

const Blog = () => {
    const posts = GetData('https://yourwordpressblog.com/wp-json/wp/v2/posts');

    return (
        <div>
            <h1>My WordPress Blog</h1>
            {posts.length ? (
                posts.map((post) => <PostDetail key={post.id} post={post} />)
            ) : (
                <p>Loading posts...</p>
            )}
        </div>
    );
};

export default Blog;

Code language: JavaScript (javascript)

Here, the Blog.jsx component calls GetData to retrieve posts from your WordPress site.

I used conditional rendering to handle loading states:

{posts.length ? (
    posts.map((post) => <PostDetail key={post.id} post={post} />)
) : (
    <p>Loading posts...</p>
)}
Code language: JavaScript (javascript)

This checks if there are any posts (posts.length). If there are, it maps through the posts and displays them with the PostDetail component. Otherwise, it shows a „Loading posts…” message until the posts are fetched. This ensures a smooth user experience while waiting for the content.

Step 3: Rendering Each Post

To render each post, I created a PostDetail.jsx component. It displays the title, an excerpt, and a link to the full post:

// PostDetail.jsx
import React from 'react';

const PostDetail = ({ post }) => {
    return (
        <div>
            <h2>{post.title.rendered}</h2>
            <div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
            <a href={post.link} target="_blank" rel="noopener noreferrer">
                Read more
            </a>
        </div>
    );
};

export default PostDetail;

Code language: JavaScript (javascript)

Using dangerouslySetInnerHTML

In the PostDetail.jsx file, I used:

<div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />

Code language: HTML, XML (xml)

I used dangerouslySetInnerHTML because WordPress returns post content (like titles and excerpts) in HTML format. React’s usual approach to setting the inner HTML of elements doesn’t work with raw HTML strings due to security concerns. Instead, dangerouslySetInnerHTML is used here to inject the HTML provided by WordPress into the component.

Known Issues

While integrating, I faced a couple of related challenges:

The API response wasn’t in JSON format at first, which led to parsing errors. This happened because I hadn’t set the WordPress permalink structure to „Post name.” Once I made that change, the REST API worked correctly, and the endpoints returned the expected data.

Final Thoughts

Integrating your WordPress blog into a React app using the WordPress REST API is a simple but effective way to merge dynamic content with React’s powerful UI capabilities. By using components and hooks, you can easily fetch and display WordPress posts, keeping the content fresh and interactive.


Opublikowano

w

, ,

przez

Tagi:

Komentarze

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *