WordPress REST API and React.js: fetch posts


Advanced

On this post we will create simple feed of WordPress posts from my blogs book sections to display in React. We won’t do component to display single post, but link to original WP blog. We will do that component in some future blog post.

We are going to create 3 files. Home.js is our frontpage where we will display our posts. It’s also where our state will live. wpClient.js is just API calls stored in seperate file. For future use it’s just good practice to have own file for those. Then we have FrontpageItem.js which includes loop and JSX for post item.

First let’s create wpClient.js. It will include our API call inside WPAPI object. We will be fetching books. All posts API call is there just as an example for reader. It won’t be used in this case.

const WPAPI = {    
     allPosts: 'http://juha.blog/wp-json/wp/v2/posts',
     books: 'http://juha.blog/wp-json/wp/v2/posts?categories=23&per_page=4',
       
}
export default WPAPI

Next we will create our main component Home.js. This is where the magic happens. So as soon as you have basic component skeleton made and you have made following imports set initial state on constructor to be empty array for books.

Then inside componentDidMount lifecycle method bring our API call for books from our WPAPI object. Then use fetch method to get stuff from API. Then we will well use ‘then’ method and corvert our API call response to json and save it to our state. Then we just pass book array from our state as a prop to FrontpageItem component we will write next.

 

import React, { Component } from 'react';

import WPAPI from '../../service/wpClient';
import FrontpageItem from '../items/FrontpageItem';

class Home extends Component {

  constructor () {
    super();
    this.state = {
      books: []
    }
 
  }

  componentDidMount (){

    const bookUrl = WPAPI.books;

    fetch(bookUrl)
    .then(response => response.json())
    .then(response => {
      this.setState({
        books: response
      })
    })
  }
 
  render() {

    
    return (

      <div className="container">
        
          <FrontpageItem posts={this.state.books} />
         
      </div>

    );
  }
}

export default Home;

Last thing to do is FrontpageItem component. This one will do looping for our array and also displays them. First let’s assign our props to posts variable. Then we will make our loop using map method. It’s kind of like for loop, but is much easier to use and makes much more sense anyway. Map method wants two arguments: first one is what we want to call single item in array and second one is index. Then inside the loop we just return what we want our individual post to render. Remember to give parent element index as key. This is important. ClassNames are just for CSS purposes so you can replace them with your own.

Then we just include our postLoop inside return. Remember to use curly braces when doing expression inside return.

import React from 'react'


class FrontpageItem extends React.Component {
  render () {
    let posts = this.props.posts

    let postLoop = posts.map((post, index)=> {
      return (
        <article key={index} className='xiong-block'>
          <a href={post.link}>
                  <h3>{post.title.rendered}</h3>
          </a>
        </article>
      )
    })

    return (
      <div>
        {postLoop}
         
      </div>
    )
  }

}

export default FrontpageItem;