Dylan  Iqbal

Dylan Iqbal

1560823578

Implementing an Infinite Scroll list in React Native

While implementing pagination in mobile devices, one has to take a different approach since space is minimal unlike the web, due to this factor, infinite scrolling has always been the go to solution, giving your users a smooth and desirable experience.

Table of Contents

In this tutorial, we will be building an infinite scroll list using the FlatList component in React Native, we will be consuming Punk API which is a free beers catalogue API.

Demo Video

Here’s a small demo video of what the end result will look like:

Setting Up

We will be using create-react-native-app to bootstrap our React Native app, run the folowing command to install it globally:

npm install -g create-react-native-app

Next we need to bootstrap the app in your preffered directory:

 react-native init react_native_infinite_scroll_tutorial

I’ll be using an android emulator for this tutorial but the code works for both IOS and Android platforms. In case you don’t have an android emulator setup follow the instructions provided in the android documentation here.

Make sure your emulator is up and running then navigate to your project directory and run the following command:

react-native run-android

This should download all required dependecies and install the app on your emulator and then launch it automatically, You should have a screen with the default text showing as follows:

Now that we have our sample app up and running, we will now install the required dependecies for the project, we will be using the Axios for making requests to the server and Glamorous Native for styling our components, run the following command to install them:

npm install -S axios glamorous-native

Directory Structure

Directory structure is always crucial in an application, since this is a simple demo app, we’ll keep this as minimal as possible:

src
├── App.js
├── components
│   ├── BeerPreviewCard
│   │   ├── BeerPreviewCard.js
│   │   └── index.js
│   ├── ContainedImage
│   │   └── index.js
│   └── Title
│       └── index.js
├── config
│   └── theme.js
└── utils
    └── lib
        └── axiosService.js

Axios Config

In order to make our axios usage easy, we will create a singleton instance of the axios service that we can import across our components:

import axios from 'axios';

const axiosService = axios.create({
  baseURL: 'https://api.punkapi.com/v2/',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// singleton instance
export default axiosService;

Card Styling

Next we will create cards to display our beer data and add some designs to it.

theme.js

This file contains the app color pallete which we will use across the app.

export const colors = {
  french_blue: '#3f51b5',
  deep_sky_blue: '#007aff',
  white: '#ffffff',
  black: '#000000',
  veryLightPink: '#f2f2f2'
};

Title.js

This file contains the card text component that we will use to display the beer name in the card.

import glamorous from 'glamorous-native';
import { colors } from '../../config/theme';

const Title = glamorous.text((props, theme) => ({
  fontFamily: 'robotoRegular',
  fontSize: 16,
  color: props.color || colors.black,
  lineHeight: 24,
  textAlign: props.align || 'left',
  alignSelf: props.alignSelf || 'center'
}));

export default Title;

ContainedImage.js

This file contains our image component which will have a resizeMode of contained in order to have the image fit within it’s containing component.

import React from 'react';
import glamorous from 'glamorous-native';

const CardImageContainer = glamorous.view((props, theme) => ({
  flex: 1,
  alignItems: 'stretch'
}));

const StyledImage = glamorous.image((props, theme) => ({
  position: 'absolute',
  top: 0,
  left: 0,
  bottom: 0,
  right: 0
}));

const ContainedImage = props => {
  return (
    <CardImageContainer>
      <StyledImage resizeMode="contain" {...props} />
    </CardImageContainer>
  );
};

export default ContainedImage;

BeerPreviewCard.js

This file contains the main card container, this is where we combine the title component and the image component to form a card that displays the beer name and image.

import React from 'react';
import glamorous from 'glamorous-native';

// app theme colors
import { colors } from '../../config/theme';

// components
import Title from '../Title';
import ContainedImage from '../ContainedImage';

const CardContainer = glamorous.view((props, theme) => ({
  height: 160,
  width: '85%',
  left: '7.5%',
  justifyContent: 'space-around'
}));

const CardImageContainer = glamorous.view((props, theme) => ({
  flex: 1,
  alignItems: 'stretch'
}));

const BeerNameContainer = glamorous.view((props, theme) => ({
  height: '30%',
  backgroundColor: colors.deep_sky_blue,
  justifyContent: 'center'
}));

const BeerPreviewCard = ({ name, imageUrl }) => {
  return (
    <CardContainer>
      <CardImageContainer>
        <ContainedImage source={{ uri: imageUrl }} />
      </CardImageContainer>
      <BeerNameContainer>
        <Title align="center" color={colors.white}>
          {name}
        </Title>
      </BeerNameContainer>
    </CardContainer>
  );
};

export default BeerPreviewCard;

Fetching Beers

The logic for fetching beers will be in App.js which is the main component of the app, we need to consume the API by making a GET request to fetch a list paginated beers:

import React, { Component } from 'react';

// axios service
import axiosService from './utils/lib/axiosService';

export default class AllBeersScreen extends Component {
  state = {
    data: [],
    page: 1,
    loading: true,
    error: null
  };

  componentDidMount() {
    this._fetchAllBeers();
  }

  _fetchAllBeers = () => {
    const { page } = this.state;
    const URL = `/beers?page=${page}&per_page=10`;

    axiosService
      .request({
        url: URL,
        method: 'GET'
      })
      .then(response => {
        this.setState((prevState, nextProps) => ({
          data:
            page === 1
              ? Array.from(response.data)
              : [...this.state.data, ...response.data],
          loading: false
        }));
      })
      .catch(error => {
        this.setState({ error, loading: false });
      });
  };

 render() {
    return (
        // map through beers and display card
    );
}

FlatList Component

So what is a FlatList component? I’ll quote the React Native docs which describes it as a performant interface for rendering simple, flat lists, supporting the most handy features this include:

We will be using a few features from the above list for our app namely footer, pull to refresh and scroll loading.

Basic Usage:

To use the FlatList component, you have to pass two main props which are RenderItem and data we can now pass the data we fetched earlier on to the FlatList component and use the BeerPreviewCard component to render a basic FlatListas follows:

export default class AllBeersScreen extends Component {
 // fetch beer request and update start from earlier on
 render() {
    return (
         <FlatList
          contentContainerStyle={{
            flex: 1,
            flexDirection: 'column',
            height: '100%',
            width: '100%'
          }}
          data={this.state.data}
          keyExtractor={item => item.id.toString()}
          renderItem={({ item }) => (
            <View
              style={{
                marginTop: 25,
                width: '50%'
              }}
            >
              <BeerPreviewCard name={item.name} imageUrl={item.image_url} />
            </View>
          )}
        />
    );
}

Reload your app and you should a view similar to this:

Scroll Loading

The main feature of infinite scrolling is loading content on demand as the user scrolls through the app, to achieve this, the FlatList component requires two props namely onEndReached and onEndReachedThreshold.

onEndReached is the callback called when the users scroll position is close to the onEndReachedThreshold of the rendered content, onEndReachedThreshold is basically a number which indicates the user’s scroll position in relation to how far it is from the end of the visible content, when the user reaches the specified position, the onEndReached callback is triggered.

A value of 0.5 will trigger onEndReached when the end of the content is within half the visible length of the list, which is what we need for this use case.

export default class AllBeersScreen extends Component {
  state = {
    data: [],
    page: 1,
    loading: true,
    loadingMore: false,
    error: null
  }; 

 // fetch beer request and update start from earlier on

  _handleLoadMore = () => {
    this.setState(
      (prevState, nextProps) => ({
        page: prevState.page + 1,
        loadingMore: true
      }),
      () => {
        this._fetchAllBeers();
      }
    );
  };

 render() {
    return (
         <FlatList
          contentContainerStyle={{
            flex: 1,
            flexDirection: 'column',
            height: '100%',
            width: '100%'
          }}
          data={this.state.data}
          renderItem={({ item }) => (
            <View
              style={{
                marginTop: 25,
                width: '50%'
              }}
            >
              <BeerPreviewCard name={item.name} imageUrl={item.image_url} />
            </View>
          )}
          onEndReached={this._handleLoadMore}
          onEndReachedThreshold={0.5}
          initialNumToRender={10}
        />
    );
  }
}

If you go back to the app and scroll down, you’ll notice the beer list been automatically loaded as you scroll down (see demo at start of tutorial).

Footer

The footer is basically the bottom part of our FlatList component, when the user scrolls down we want to show a loader when the content is been fetched, we can achieve this using the ListFooterComponent prop where we will pass a function that returns an ActivityIndicator component wrapped in a View component:

  _renderFooter = () => {
    if (!this.state.loadingMore) return null;

    return (
      <View
        style={{
          position: 'relative',
          width: width,
          height: height,
          paddingVertical: 20,
          borderTopWidth: 1,
          marginTop: 10,
          marginBottom: 10,
          borderColor: colors.veryLightPink
        }}
      >
        <ActivityIndicator animating size="large" />
      </View>
    );
  };

 render() {
    return (
         <FlatList
          // other props
          ListFooterComponent={this._renderFooter}
        />
    );
  }

Now when scrolling a loader will show on the screen while the content is loading (see demo at start of tutorial)

Pull To Refresh

Pull to refresh functionality is widely used in almost every modern application that uses network activity to fetch data, to achieve this in the FlatList, we need to pass the onRefresh prop which triggers a callback when the user carries a pull down gesture at the top of the screen:

  _handleRefresh = () => {
    this.setState(
      {
        page: 1,
        refreshing: true
      },
      () => {
        this._fetchAllBeers();
      }
    );
  };

 render() {
    return (
         <FlatList
          // other props
          onRefresh={this._handleRefresh}
          refreshing={this.state.refreshing}
        />
    );
  }

Now when you try pulling down from the top part of the screen a loader will appear from the top and the content will be refetched.

Extra Props Explained:

initialNumToRender - This is the number of items we want to render when the app loads the data keyExtractor_ - _Used to extract a unique key for a given item at the specified index

Conclusion:

Infinite scrolling grants your users a smooth experience while using you app and is an easy way for your to deliver presentable and well ordered content for your users.

You can access the code here

Learn More

Modern React with Redux

Become a JavaScript developer - Learn (React, Node,Angular)

The Complete React Web Developer Course (2nd Edition)

Node with React: Fullstack Web Development

Beginner Full Stack Web Development: HTML, CSS, React & Node

React JS and Redux - Mastering Web Apps

React 16 - The Complete Guide (incl. React Router 4 & Redux)

MERN Stack Front To Back: Full Stack React, Redux & Node.js

#javascript #reactjs #react-native

What is GEEK

Buddha Community

Implementing an Infinite Scroll list in React Native
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms?

React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. Hire Dedicated React Native Developer from top React Native development company, HourlyDeveloper.io to design a spectacular React Native application for your business.

Consult with experts:- https://bit.ly/2A8L4vz

#hire dedicated react native developer #react native development company #react native development services #react native development #react native developer #react native

Juned Ghanchi

1621573085

React Native App Developers India, React Native App Development Company

Expand your user base by using react-native apps developed by our expert team for various platforms like Android, Android TV, iOS, macOS, tvOS, the Web, Windows, and UWP.

We help businesses to scale up the process and achieve greater performance by providing the best react native app development services. Our skilled and experienced team’s apps have delivered all the expected results for our clients across the world.

To achieve growth for your business, hire react native app developers in India. You can count on us for all the technical services and support.

#react native app development company india #react native app developers india #hire react native developers india #react native app development company #react native app developers #hire react native developers

Hire Dedicated React Native Developers - WebClues Infotech

Being one of the emerging frameworks for app development the need to develop react native apps has increased over the years.

Looking for a react native developer?

Worry not! WebClues infotech offers services to Hire React Native Developers for your app development needs. We at WebClues Infotech offer a wide range of Web & Mobile App Development services based o your business or Startup requirement for Android and iOS apps.

WebClues Infotech also has a flexible method of cost calculation for hiring react native developers such as Hourly, Weekly, or Project Basis.

Want to get your app idea into reality with a react native framework?

Get in touch with us.

Hire React Native Developer Now: https://www.webcluesinfotech.com/hire-react-native-app-developer/

For inquiry: https://www.webcluesinfotech.com/contact-us/

Email: sales@webcluesinfotech.com

#hire react native developers #hire dedicated react native developers #hire react native developer #hiring a react native developer #hire freelance react native developers #hire react native developers in 1 hour

Factors affecting the cost of hiring a React Native developer in USA - TopDevelopers.co

Want to develop app using React Native? Here are the tips that will help to reduce the cost of react native app development for you.
Cost is a major factor in helping entrepreneurs take decisions about investing in developing an app and the decision to hire react native app developers in USA can prove to be fruitful in the long run. Using react native for app development ensures a wide range of benefits to your business. Understanding your business and working on the aspects to strengthen business processes through a cost-efficient mobile app will be the key to success.

#best react native development companies from the us #top react native app development companies in usa #cost of hiring a react native developer in usa #top-notch react native developer in usa #best react native developers usa #react native