This is second part of article React Native App with WordPress . In last part we learned how we can use WordPress as back-end for React Native App and create endpoints to get data. In this part we will see how we can use the React Native FlatList component to render data with pagination and refresh feature. Enough Talk! Now lets start with coding.
First we will add all the required packages to our package.json file and then the file will look like this :
{ "name": "MyNewsApp", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest" }, "dependencies": { "react": "16.0.0-alpha.6", "react-native": "0.43.0", "react-native-elements": "^0.11.1", "react-native-render-html": "^3.6.0", "react-native-vector-icons": "^4.0.1" }, "devDependencies": { "babel-jest": "22.0.6", "babel-preset-react-native": "4.0.0", "jest": "22.0.6", "react-test-renderer": "16.0.0-alpha.6" }, "jest": { "preset": "react-native" } }
So, you can see we have added three new packages react-native-elements, react-native-render-html and react-native-vector-icons.
Now we will import the packages in our NewsList.js file and our file will have the code below :
import React, { Component } from 'react'; import { Text, View, FlatList, ActivityIndicator, AppRegistry } from 'react-native'; import { List, ListItem } from "react-native-elements";
Next we will add constructor to NewsList component and initialize state like below :
export default class NewsList extends Component { constructor(props) { super(props); this.state = { loading: false, data: [], page: 1, refreshing: false, siteTitle: '' }; }
In the above code, state variable loading will hold the status if data is loading or has been loaded, data variable will hold data that will be fetched, page will hold current page no of list, refreshing will hold if user refreshed list or not and siteTitle will hold the title of website that will be fetched.
Next, we will write the function below, to fetch remote data :
fetchData = () => { const { page } = this.state; const url = `http://3arabmagazine.com/wp-json/wp/v2/posts?page=${page}&results=20`; this.setState({ loading: true }); fetch(url) .then(res => { return res.json() }) .then(res => { const arrayData = [...this.state.data, ...res] this.setState({ data: page === 1 ? res : arrayData, loading: false, refreshing: false }); }) .catch(error => { console.log(error); this.setState({ loading: false }); }); };
In the above code, We are fetching posts from WordPress website using the endpoint to fetch posts.
Next, we will use componentDidMount lifecycle method to get the website title and website post (using the fetchData function we created above). Below is the code for the same :
componentDidMount() { const urlSiteDetail = "http://3arabmagazine.com/wp-json" fetch(urlSiteDetail) .then(res => { return res.json() }) .then(res => { this.setState({ siteTitle: res.name }); }) .catch(error => { }); this.fetchData(); }
Next we will user renderHeader and renderFooter methods to set-title and show load more indicator respectively like below :
renderHeader = () => { return (<Text style={{ alignSelf: "center", fontWeight: "bold", fontSize: 20, marginBottom: 10}}>{this.state.siteTitle}</Text>) }; renderFooter = () => { return ( <View style={{ paddingVertical: 20, borderTopWidth: 1, borderColor: "#CED0CE" }} > <ActivityIndicator animating size="large" /> </View> ); };
Below is the code that will be executed when user will refresh list :
handleRefresh = () => { this.setState( { page: 1, refreshing: true }, () => { this.fetchData(); } ); };
Below is the code that will be called when user will reach end of the list and more data need to be loaded :
handleLoadMore = () => { this.setState( { page: this.state.page + 1 }, () => { this.fetchData(); } ); };
Finally we will render data using FlatList component like below :
render() { return ( <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }} > <FlatList data={this.state.data} keyExtractor={item => item.id} ListHeaderComponent={this.renderHeader} ListFooterComponent={this.renderFooter} renderItem={({ item }) =>{ if(((item.title.rendered).trim() != "") && ((item.title.rendered).trim() != "Copy")) return (<View><ListItem roundAvatar title={<HTML html={`${item.title.rendered}`} />} avatar={{ uri: item.featured_image_urls.thumbnail }} containerStyle={{ borderBottomWidth: 0 }} /> <View style={{ height: 1, width: "86%", backgroundColor: "#CED0CE", marginLeft: "14%" }} /></View> ) }} onRefresh={this.handleRefresh} refreshing={this.state.refreshing} onEndReached={this.handleLoadMore} onEndReachedThreshold={50} /> </List> ); }
Conclusion
So, in this article we learned two main things.
- How to fetch data from WordPress endpoint
- How to render data using FlatList component with pagination and refresh list feature
If you find this article information please do subscribe to our news letter and YouTube channel and stay tuned for more of such awesome tutorials.
Video Tutorial