Using Axios to Fetch WordPress Post Data from WP-JSON Rest API Endpoints in React

Using Axios to Fetch WordPress Post Data from WP-JSON Rest API Endpoints in React

So, you want to use Axios to fetch WordPress post data from WP-JSON REST API endpoints in react, huh?

Maybe you're doing some WP theming or creating a front-end for a headless WordPress website and you want to pull in post data to display on the page. Whatever – cool.

Well, here's one way to go about using React and Axios to fetch post data from your WordPress back-end, so you can render it on the front-end.

Ingredients

You'll need a few key ingredients to make this WordPress recipe work.

  • A WordPress site (i.e. a back-end with content)
  • ReactJS
  • Axios

Enabling Custom Post Types

By default, WordPress posts and pages are exposed to the WP Rest API, but if you want to access custom post types you'll need to enable REST functionality when you register them.

Simply put, add 'show_in_rest' => true to your custom post type's args.

add_action('init', function() {
	register_post_type('toaster', [
		'public' => true,
		'label' => 'Toasters',
		'show_in_rest' => true // <-- ADD THIS LINE
	]);
});

Recipe

Here's a ReactJS recipe for success. You can use the following to create a component that displays a posts list.

class PostList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
    this.createMarkup = this.createMarkup.bind();
  };
  
  componentDidMount() {
        axios.get("https://your-wordpress-site.com/wp-json/wp/v2/posts")
        .then(posts => {
	        this.setState({
            	posts: posts.data
        	});
        });
  };
  
  createMarkup(html) {
    return { __html: html };
  };
  
  render() {
    return (
      <div>
        {this.state.posts.map(post => (
          <Link to={`/${post.slug}`} key={post.id}>
            <div className="card" key={post.id}>
              <div className="card-content">
                <h3 dangerouslySetInnerHTML={this.createMarkup(post.title.rendered)}></h3>
                <div
                  dangerouslySetInnerHTML={this.createMarkup(
                    post.excerpt.rendered
                  )}
                />
              </div>
            </div>
          </Link>
        ))}
      </div>
    );
  }
}

export default PostList;

Use this code snippet as a starting point to template the front-end of your WordPress site.

The HTML markup and CSS styling can be done any way you want – what's important here is that you're using Axios and the WP-JSON Rest API to get posts data to display in a ReactJS component.

Bonus: Enable WP Advanced Custom Fields REST API Endpoints

You can make fetching WordPress posts data with Axios even more powerful by exposing your site's Advanced Custom Fields field endpoints to the WP Rest API.

The simplest way is using the free WordPress plugin ACF to REST-API. After installing and activating this plugin, your ACF fields can be accessed similar to the rest of your post's data.