React-native pagination example using array method map

Hi Guys, In this article, we are going to learn about the React-native pagination example using array method map, as we all know many developers use FlatList component to display the list with pagination but in this article, we will learn with the help of JSX array method in react-native, also we are using NativeBase.io in this example which is open source and minimize code for UI design and provide a special type of component to design UI in react-native. so let’s start with an example

To learn infinity list with FlatList check this post

1. Create a new project

react-native init ProjectName

Install NativeBase.io using the following command

npm install native-base --save

2. Import the following components

Import react-native as well as Nativebase components like below

import React, {Component} from 'react';

import {
  Header,
  Container,
  Title,
  Content,
  Card,
  CardItem,
  Spinner,
} from 'native-base';

import {Image, Text} from 'react-native';

3. Define variables

Define variables for pageNumber and state

let pageNumber = 1;

Inside call constructor define the following variables

  constructor(props) {
    super(props);
    this.state = {
      JSONResult: [],
      datasetState: null,
      loading: false,
    };
  }

4. Fetch call for pagination

As you can see in the below code I have pass pageSize and boolean to display loadMore loader at the bottom. In response, I have added JSON response in the previous Arraylist and update pageNumber using pageNumber = pageNumber + 1;

 getListCall(pageSize, bool) {
    var that = this;
    this.setState({loading: true, onLoadMore: bool});
    var url =
      'https://techup.co.in/api/products?page=' +
      pageNumber +
      '&per_page=' +
      pageSize;
    console.log('-----------url:' + url);

    fetch(url, {method: 'GET'})
      .then(response => response.json())
      .then(responseJson => {
        that.setState({
          // JSONResult: result,
          JSONResult: [...this.state.JSONResult, ...responseJson],
          loading: false,
          onLoadMore: false,
        });
        pageNumber = pageNumber + 1;
      })
      .catch(function(error) {
        console.log('-------- error ------- ' + error);
        this.setState({loading: false});
        alert('result:' + error);
      });
  }

We have to call this function in componentWillMount.

 componentWillMount() {
    this.getListCall(10, false);
  }

5. Pagination using the map array

In NativeBase we have to wrap everything inside <Container>… </Container> component. Inside the Container, I have added the Content component. Using content component we can trigger the event when the user reached the end of the page to find out the end we have created a new function isCloseToBottom this function will return true if the user is close to the bottom at that time we have to call fetch method to get next page response let’ see below source code

Function to check scroll reached end of page

// Function to check scroll reached end of page 
isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => { 
    return layoutMeasurement.height + contentOffset.y >= contentSize.height - 1; 
};
  render() {
    if (this.state.loading && pageNumber == 1) {
      return (
        <Container>
          <Header />
          <Content>
            <Spinner color="red" />         //<--- First time API call loader
          </Content>
        </Container>
      );
    } else {
      return (
        <Container>
          <Header>
            <Title>Pagination Example</Title>
          </Header>
          <Content
            style={{flex: 1}}
            scrollEventThrottle={300}
            onScroll={({nativeEvent}) => {
              if (this.isCloseToBottom(nativeEvent)) {    //<---Check if reached end of page
                // console.warn('Reached end of page');
                this.getListCall(10, true);             //<---- LoadMore API call
              }
            }}>
            {this.state.JSONResult.map(record => {
              return (
                <Card style={{margin: 10}}>
                  <CardItem>
                    <Image
                      style={{resizeMode: 'cover', width: '100%', height: 150}}
                      source={{
                        uri:
                          record.image
                      }}
                    />
                  </CardItem>
                </Card>
              );
            })}
          </Content>
          {this.state.onLoadMore ? <Spinner color="red" /> : null}    //<-- Bottom LoadeMore Loader
        </Container>
      );
    }
  }

6. Full Source code

import React, {Component} from 'react';

import {
  Header,
  Container,
  Title,
  Content,
  Card,
  CardItem,
  Spinner,
} from 'native-base';

import {Image, Text} from 'react-native';

let pageNumber = 1;

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      JSONResult: [],
      datasetState: null,
      loading: false,
    };
  }

  componentWillMount() {
    this.getListCall(10, false);
  }

  getListCall(pageSize, bool) {
    var that = this;
    this.setState({loading: true, onLoadMore: bool});
    var url =
      'https://techup.co.in/api/products?page=' +
      pageNumber +
      '&per_page=' +
      pageSize;
    console.log('-----------url:' + url);

    fetch(url, {method: 'GET'})
      .then(response => response.json())
      .then(responseJson => {
        that.setState({
          // JSONResult: result,
          JSONResult: [...this.state.JSONResult, ...responseJson],
          loading: false,
          onLoadMore: false,
        });
        pageNumber = pageNumber + 1;
      })
      .catch(function(error) {
        console.log('-------- error ------- ' + error);
        this.setState({loading: false});
        alert('result:' + error);
      });
  }

  isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => {
    return layoutMeasurement.height + contentOffset.y >= contentSize.height - 1;
  };

  render() {
    if (this.state.loading && pageNumber == 1) {
      return (
        <Container>
          <Header />
          <Content>
            <Spinner color="red" />
          </Content>
        </Container>
      );
    } else {
      return (
        <Container>
          <Header>
            <Title>Pagination Example</Title>
          </Header>
          <Content
            style={{flex: 1}}
            scrollEventThrottle={300}
            onScroll={({nativeEvent}) => {
              if (this.isCloseToBottom(nativeEvent)) {
                // console.warn('Reached end of page');
                this.getListCall(10, true);
              }
            }}>
            {this.state.JSONResult.map(record => {
              return (
                <Card style={{margin: 10}}>
                  <CardItem>
                    <Image
                      style={{resizeMode: 'cover', width: '100%', height: 150}}
                      source={{
                        uri:
                           record.image
                      }}
                    />
                  </CardItem>
                </Card>
              );
            })}
          </Content>
          {this.state.onLoadMore ? <Spinner color="red" /> : null}
        </Container>
      );
    }
  }
}

7. Output

React-native pagination example using array method map

Thank you 🙂

Leave a Reply

Your email address will not be published.