Now that we know how to create a REST API Endpoint in WordPress let’s get React Native to call this information into the App.
Note, I will not go into the details of creating a React Native App, but just explain how to retrieve and display the data from WordPress into you app.
So, first of all, we will need to know what the WordPress REST API Endpoint is.
In my previous post I defined the namespace as “jemarea/v1/” and the base as “jemarea-posts”. Our new URL for the REST API will be:
https://<your-domain.com>/wp-json/jemarea/v1/jemarea-posts
Please note the HTTPS! This is especially important when you want to use a REST API link to modify content inside your wordpress.
So here are the first elements you will need in your component:
import React, { Component } from 'react'; import { StyleSheet, View, Text } from 'react-native'; import axios from 'axios'; // https://github.com/archriss/react-native-render-html import HTML from 'react-native-render-html'; const cnst_wp_rest_api_link = 'https://<your-domain.com>/wp-json/jemarea/v1/jemarea-posts';
This looks like a good start.
Axios is a lightweight HTTP client and will help us to fetch the information over the internet. To install it, you will have to use YARN or NPM:
# Yarn $ yarn add axios # npm $ npm install axios --save
I am also using react-native-render-html. See the link that I am providing in the code for more information.
Now let’s write the code that will fetch this information:
class myScreen extends Component { state = { posts: [] }; componentDidMount() { // Once the component is mounted, we can start retrieving the posts this->getMyPosts(); } getMyPosts() { // use Axios axios .get(cnst_wp_rest_api_link) .then((response) => { // get some logs to see how data is coming in console.log("RESPONSE: " + JSON.stringify(response.data)); this.setState({ posts: response.data }); }) .catch(error => alert("ERROR: " + error)); } // Create the content get_content() { return this.state.posts.map( mypost => { return (<View key={mypost.ID} style={{marginTop: 30}}> <HTML baseFontStyle={{'fontSize': 22}} html={mypost} /> </View>) } ); render() { return ( <View > {this.get_content()} </View> ) } }; export default myScreen;
Leave a Reply