Mega Bundle Sale is ON! Get ALL of our React Native codebases at 95% OFF discount 🔥

As we wrap up the work on our fully functional React Native WordPress template (yes, we launched it and couldn’t be prouder of the result!), I realized that many React Native developers will face the task of integrating WordPress REST API with React Native. As a result, I decided to share our learnings, in order to help out programmers who are building their React Native apps with a WordPress backend.

wordpress rest api react native

As most of you already know, WordPress comes with a REST API out of the box. If you don’t believe me, just check out this link https://www.instamobile.io/wp-json/wp/v2/posts. It returns a paginated JSON response with all posts of our blog. I swear I only installed WordPress and did not do any extra magic. Try out the exact same URL, but for your blog, and you’ll be mindblown. Here’s a snippet of what the WordPress API returns in our case:

wordpress rest api

Now, what your React Native News Reader app has to do in order to display these beautifully formatted posts is to fetch them via an HTTP request. Fortunately, this is a simple task in React Native and even beginners should have done it at least once. Fetching data in React Native from a WordPress API is as simple as:

getPosts() {
    return fetch(
      "https://instamobile.io/wp-json/wp/v2/posts?page=" + this.state.page
    )
    .then(response => response.json())
    .then(responseJson => {
      this.setState(prevState => ({
        posts: [...prevState.posts, ...responseJson],
        isLoading: false
      }));
    })
    .catch(error => {
      console.error(error);
    });
 }

The “fetch” method makes a network request (GET) to a given URL. In our case, we provide the REST API URL to our WordPress blog (notice the instamobile.io URL from the 3rd line). Once the response comes back, we parse it as JSON and then append the posts at the end of the existing (already displayed) articles. In practice, this is basically updating the state of the React component.

Notice the fact that the WordPress REST API is paginated, so in order to fetch a specific page, you need to provide an extra param within the GET request, named “page”. We store the current page in the state object, so that we always fetch a new page, as the user scrolls down the list of blog posts.

Additionally, in the state object, we also store an “isLoading” boolean variable, to inform the rendered component whether there is a fetch request in process. In our React Native WordPress app, we display a spinner at the bottom of the screen to let the users know something is happening and they should wait for the newly fetched articles.

Without further ado, here’s how you display the retrieved WordPress articles in React Native:

return (
  <FlatList
    data={this.state.posts}
    renderItem={({ item }) => (
      <News
        navigation={this.props.navigation}
        title={item.title.rendered}
        image={item.acf.author_photo}
        day={item.date}
        data={item}
      />
    )}
    keyExtractor={item => item.id.toString()}
    onEndReached={this.handleLoadMore}
    onEndReachedThreshold={1}
  />
);

We are just using a plain old FlatList to display the list of articles. Notice that for each item, we display a custom component named “News” that takes a bunch of properties and renders them. The critical observation here is that we are using the fields from the JSON response (“title.rendered”, “acf.author_photo”, etc). This is where the magic happens – we’ve just linked the WordPress JSON API to a React Native component that displays them.

“ACF” stands for “Advanced Custom Fields”, which is a WordPress plugin allowing you to add custom fields to any WordPress post. This plugin comes in very handy if you want to pass extra information from the WordPress post to the React Native app (like the author image, as in the example above). Other examples of custom fields can be cover photo, author name, tags, colors, shorter title, etc. Here’s a screenshot of what the ACF plugin gives you for each post in the WordPress Admin Dashboard:

react native advanced custom fields

I hope this tutorial has been useful. Good luck in making your own React Native app with WordPress REST API backend. If you got any questions, let me know in the comments. Peace out!


Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart