How to Use WordPress with React: Simple Integration Guide
You can use
React with WordPress by fetching data from the WordPress REST API and displaying it in React components. This lets you build a React frontend that shows WordPress content dynamically without using PHP templates.Syntax
To use WordPress with React, you fetch data from WordPress's REST API endpoint, usually at /wp-json/wp/v2/posts. Then, you use React's useEffect hook to load data and useState to store it.
Key parts:
fetch(): gets data from WordPress APIuseEffect(): runs fetch once on component loaduseState(): stores posts datamap(): loops over posts to display
javascript
import React, { useState, useEffect } from 'react'; function WordPressPosts() { const [posts, setPosts] = useState([]); useEffect(() => { fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts') .then(response => response.json()) .then(data => setPosts(data)); }, []); return ( <div> {posts.map(post => ( <article key={post.id}> <h2>{post.title.rendered}</h2> <div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} /> </article> ))} </div> ); } export default WordPressPosts;
Output
A list of WordPress posts with titles and excerpts displayed on the page.
Example
This example shows a React component that fetches posts from a WordPress site and displays their titles and excerpts. It demonstrates how to connect React to WordPress content using the REST API.
javascript
import React, { useState, useEffect } from 'react'; function WPBlog() { const [posts, setPosts] = useState([]); useEffect(() => { fetch('https://demo.wp-api.org/wp-json/wp/v2/posts') .then(res => res.json()) .then(data => setPosts(data)) .catch(err => console.error('Error fetching posts:', err)); }, []); return ( <main> <h1>WordPress Posts</h1> {posts.length === 0 && <p>Loading posts...</p>} {posts.map(post => ( <article key={post.id}> <h2>{post.title.rendered}</h2> <section dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} /> </article> ))} </main> ); } export default WPBlog;
Output
Page shows "WordPress Posts" heading and a list of post titles with excerpts fetched live from WordPress.
Common Pitfalls
- Not enabling the WordPress REST API or using a site that blocks it.
- Trying to fetch data without handling CORS errors from WordPress.
- Using
dangerouslySetInnerHTMLwithout sanitizing content can cause security risks. - Not handling loading or error states in React leads to poor user experience.
Always check your WordPress site allows REST API access and handle fetch errors gracefully.
javascript
/* Wrong way: No error handling and no loading state */ useEffect(() => { fetch('https://your-site.com/wp-json/wp/v2/posts') .then(res => res.json()) .then(data => setPosts(data)); }, []); /* Right way: Add loading and error states */ const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('https://your-site.com/wp-json/wp/v2/posts') .then(res => { if (!res.ok) throw new Error('Network error'); return res.json(); }) .then(data => { setPosts(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []);
Quick Reference
- Use WordPress REST API endpoints like
/wp-json/wp/v2/poststo get content. - Use React hooks
useEffectanduseStateto fetch and store data. - Handle loading and error states for better UX.
- Use
dangerouslySetInnerHTMLcarefully to render HTML content. - Consider CORS and authentication if needed.
Key Takeaways
Fetch WordPress content using the REST API to use it in React apps.
Use React hooks to load and display WordPress data dynamically.
Handle loading and errors to improve user experience.
Be cautious with rendering HTML from WordPress to avoid security risks.
Ensure your WordPress site allows REST API access and CORS requests.