DEV Community

Cover image for Build WordPress App with React Native #12: Categories index
0xAirdropfarmer
0xAirdropfarmer

Posted on • Originally published at kriss.io on

Build WordPress App with React Native #12: Categories index

This series intends to show how I build app to serve content from my WordPress blog by using react native. Since my blog is talking about react-native, the series and the articles are interconnected. We will learn how to set-up many packages that make our lives comfortable and learn how to deal with WordPress APIs. Here, the most prominent features talked about in the book are the dark theme , offline mode, infinite scroll and many more. You can discover much more in this series.this inspiration to do this tutorial series came from the React Native Mobile Templates

In case of wanting to learn from the beginning, all the previous parts for this tutorial series are available below:

  1. Build WordPress Client App with React Native #1: Overview
  2. Build WordPress Client App with React Native #2: Setting Up Your Environment
  3. Build WordPress Client App with React Native #3: Handle Navigation with React navigation
  4. Build WordPress Client App with React Native #4: Add Font Icon
  5. Build WordPress Client App with React Native #5 : Home Screen with React native paper
  6. Build WordPress Client App with React Native #6 : Using Html renderer and Moment
  7. Build WordPress Client App with React Native #7: Add pull to refresh and Infinite scroll
  8. Build WordPress Client App with React Native #8: Implementing SinglePost Screen
  9. Build WordPress Client App with React Native #9: implement simple share
  10. Build WordPress Client App with React Native #10: Setup and save bookmark
  11. Build WordPress Client App with React Native #11: Remove and Render Bookmark

Here, we are going to implement the Categories screen. This screen will contain the list of categories related to the article posts. And on clicking on these categories, we will navigate to the posts which are based on that respective category.

The implementation is simple. We are going to fetch the categories data and display it with the FlatList component. And by using the TouchableOpacity component, we will navigate to the new list screen which will display the list of article posts based on that category.

First, we need to open the Categories.js file and import necessary components and define some required state as well as shown in the code snippet below:

    import React from 'react';
    import {
      FlatList,
      ScrollView,
      View,
      TouchableOpacity,
    } from 'react-native';
    export default class Categories extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          loading: false,
          categories: [],
        };
      }

Here, we have defined the loading state to display the loader on fetching of
data and categories to store the categories list data. Now, we need to create
a function called fetchCategorie() which will fetch all the categories data
from the WordPress API as shown in the code snippet below:

    componentDidMount() {
        this.fetchCategorie();
      }
      async fetchCategorie() {
        this.setState({ loading: true });
        const response = await fetch(`https://kriss.io/wp-json/wp/v2/categories`);
        const categories = await response.json();
        this.setState({
          categories: categories
        });
      }

Here, we have fetched the categories data using the fetch function. Then, we
parse it to JSON and store it in the categories state. Then, we have called
the function in the componentDidMount hook.

Now, we need to add the data to FlatList in the render() function of
Categories screen as shown in the code snippet below:

    render() {
        return (
          <ScrollView>
            <FlatList
              data={this.state.categories}
              renderItem={({item}) => (
                <TouchableOpacity
                  onPress={() =>
                    this.props.navigation.navigate('CategorieList', {
                      categorie_id: item.id,
                      categorie_name: item.name
                    })
                  }>
                  <Card>
                    <Card.Content>
                      <Title>{item.name}</Title>
                    </Card.Content>
                  </Card>
                </TouchableOpacity>
              )}
              keyExtractor={(item, index) => index}
            />
          </ScrollView>
        );
      }
    }

Here, we have the template in the FlatList component. The FlatList is
configured with data from for categories data and keyExtractor prop for the
key data. Then, the renderItem prop returns the template for the categories
list. The template has the TouchableOpacity as the parent component which has
navigation configured to the CategorieList screen. We are going to implement the
CategorieList screen later. Then, we have used the Card component and its
subcomponents to display the category name.

Hence, we will get the following result in the emulator screens:

As we can see, we have got the categories list in the Categories list. By
tapping on any list item, we need to navigate to the CategorieList screen which
will display the articles related to that category. But, we get error because we
have not yet implemented the screen.

For that, we need to create a new screen called CategoriesList.js file in the
‘./screens/’ folder.

Then, we need to make the imports and also define state as shown in the code
snippet below:

    import React from 'react';
    import {View, FlatList, TouchableOpacity} from 'react-native';
    import {Card, Title, Paragraph} from 'react-native-paper';
    import moment from 'moment';
    import HTML from 'react-native-render-html';
    export default class CategorieList extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          posts: [],
        };
      }

Here, we have defined the posts state which will store the posts fetched based
in the category id.

Next, we need to add the CategorieList screen to the stack navigator in the
App.js file. For that, we need to make use of the code from the following code
snippet:

    import CategorieList from './screens/CategoriesList';
    const StackNavigator = createStackNavigator({
      DashboardTabNavigator: DashboardTabNavigator,
      SinglePost: SinglePost,
      CategorieList : CategorieList
    });

Then, we need to implement the function called fetchPost which is used to
fetch the article posts based on the particular category. The overall
implementation of the function is provided in the code snippet below:

    componentDidMount() {
       this.fetchPost();
     }
     async fetchPost() {
       let categorie_id = this.props.navigation.getParam('categorie_id');
       const response = await fetch(
         `https://kriss.io/wp-json/wp/v2/posts?categories=${categorie_id}`,
       );
       const post = await response.json();
       this.setState({posts: post});
     }

Here, we have fetched the posts using fetch() function from the WordPress API
with category id value. Then, we parsed it and stored it in the posts state
variable. Lastly, we called the function in the componentDidMount hook of the
CategorieList screen.

Now, we need to set up the template of the CategorieList screen to display the
list of article post based on the particular category. For that, we need to use
the code from the following code snippet in the render() function

    render() {
        categorie_title = this.props.navigation.getParam('title');
        return (
          <View>
            <Title style={{marginLeft: 30}} >{categorie_title}</Title>
            <FlatList
              data={this.state.posts}
              renderItem={({item}) => (
                <TouchableOpacity
                  onPress={() =>
                    this.props.navigation.navigate('SinglePost', {
                      post_id: item.id,
                    })
                  }>
                  <Card>
                    <Card.Content>
                      <Title>{item.title.rendered}</Title>
                      <Paragraph>
                        Published on {moment(item.date, 'YYYYMMDD').fromNow()}
                      </Paragraph>
                    </Card.Content>
                    <Card.Cover source={{uri: item.jetpack_featured_media_url}} />
                    <Card.Content>
                      <HTML html={item.excerpt.rendered} />
                    </Card.Content>
                  </Card>
                </TouchableOpacity>
              )}
              keyExtractor={item => item.id}
            />
          </View>
        );
      }
    }

Here, we have used the FlatList component to list the List of articles just as in the Home screen. Then, we have added the navigation to the SinglePost screen using the TouchableOpacity as the parent component.

Hence, we will get the following result in the emulator screens:

As we can see, we can successfully navigate to the CategorieList screen from the Categories screen. And by tapping on articles, we can navigate to the SinglePost screen.

Summary

In this chapter, we learned how to implement the overall UI of the Categories screen as well as the CategorieList screen. We learned how to fetch the categories of different posts from the WordPress API. Then, we implemented the navigation to the CategorieList screen where we learned how to fetch the articles post based on the category id and display them as a list. Then, by clicking on the article posts we navigated to the SinglePost screen.

The post Build WordPress Client App with React Native #12: Categories screen appeared first on Kriss.

Top comments (0)