Elvis Miranda

Elvis Miranda

1558605169

How to Use FlatList | React Native FlatList Tutorial

There have been a quite a few ways to create a scrolling list in React Native, most notably they have been the ScrollView and the ListView. Each have their strengths and weaknesses. Since v0.43 of React Native we’ve had access to two new list views, the FlatListand the SectionList. Today we will take a look at how to use the FlatList component.

What is it?

What is the FlatList component? It’s an easy way to make an efficient scrolling list of data. Not only is it efficient but it’s got an incredibly simple API to work with. If you’ve used or are familiar with the ListView component it’s very similar, just better in (almost) every way. 😀 No longer do you have to format the data — you can just pass it an array of data and get to rendering right away.

Basic Usage

There are two primary props you need to know about in a FlatList and that’s data and renderItem. The first is an array of data used to create the list, typically an array of objects, and the second is the function that will take an individual element of the data array and render a component for it.

Data will come from the Random User Generator API and React Native Elements will be used for the interface.

Full source code is available on GitHub.

In the boilerplate of this tutorial the app will make a request to the Random User Generator API and store the response from that in component state. Browse the code below to get an understanding of it.

FlatListDemo.js

import React, { Component } from "react";
import { View, Text, FlatList } from "react-native";

class FlatListDemo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data: [],
      page: 1,
      seed: 1,
      error: null,
      refreshing: false,
    };
  }

  componentDidMount() {
    this.makeRemoteRequest();
  }

  makeRemoteRequest = () => {
    const { page, seed } = this.state;
    const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
    this.setState({ loading: true });
    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: page === 1 ? res.results : [...this.state.data, ...res.results],
          error: res.error || null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({ error, loading: false });
      });
  };

  render() {
    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text>Coming soon...</Text>
      </View>
    );
  }
}

export default FlatListDemo;

You’ll also point the index.ios.js and index.android.js files to reference the FlatListDemo.js file you created.

With that completed you can go ahead and actually start rendering the data. To do so the first thing you want to do is import { List, ListItem } from "react-native-elements"; so you have the necessary components to render the data. The remainder of the work will take place in the render method. First the scaffolding:

*FlatListDemo.js *

render() {
  return (
    <List>
      <FlatList
        ...
      />
    </List>
  );
}

You now need to pass an array of data to the FlatList via the data prop. That’s available on this.state.data.

FlatListDemo.js

render() {
  return (
    <List>
      <FlatList
        data={this.state.data}
      />
    </List>
  );
}

Then you want to render the content with the renderItem prop. The function is passed a single argument, which is an object. The data you’re interested in is on the item key so you can use destructuring to access that from within the function. Then return a component using that data.

FlatListDemo.js

render() {
  return (
    <List>
      <FlatList
        data={this.state.data}
        renderItem={({ item }) => (
          <ListItem
            roundAvatar
            title={`${item.name.first} ${item.name.last}`}
            subtitle={item.email}
            avatar={{ uri: item.picture.thumbnail }}
          />
        )}
      />
    </List>
  );
}

Now with the application running, and after waiting about a second for a response from the server you should see something like this (the exact data may be slightly different).

Notice that error on the bottom? That’s warning that the elements of the list are missing keys. These unique keys are what allow the VirtualizedList (which is what FlatList is built on) to track items and aids in the efficiency of the list. I won’t dive into it but just know that it’s important.

To alleviate this issue you want to choose a piece of data that is unique to each item. In this case you can use the user’s email address because that will be unique to each item. You can then use the keyExtractor prop to specify which piece of data should be used as the key.

render() {
  return (
    <List>
      <FlatList
        ...
        keyExtractor={item => item.email}
      />
    </List>
  );
}

Now the warning no longer shows up.

Separator

Let’s say you don’t have separators already in your app and you want to, but you don’t want to render them at the top or bottom of the list. You could add a borderBottom on every element except the last one…or you could use the ItemSeparatorComponent prop which will take care of all the logic for you.

For this example the first thing you need to do is remove all the borders in the app.

*FlatListDemo.diff *

render() {
  return (
    <List 
+      containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}
    >
      <FlatList
        data={this.state.data}
        renderItem={({ item }) => (
          <ListItem
            roundAvatar
            title={`${item.name.first} ${item.name.last}`}
            subtitle={item.email}
            avatar={{ uri: item.picture.thumbnail }}
+            containerStyle={{ borderBottomWidth: 0 }}
          />
        )}
        keyExtractor={item => item.email}
      />
    </List>
  );
}

You then want to create the separator component. It’s very simple but instead of being the full width of the screen it’s going to (approximately) start where the text does.

FlatListDemo.js

class FlatListDemo extends Component {
  // ...

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%"
        }}
      />
    );
  };

  // ...
}

and then you can go ahead and use that by simply adding ItemSeparatorComponent={this.renderSeparator} to the FlatList component.

FlatListDemo.js

render() {
  return (
    <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
      <FlatList
        ...
        ItemSeparatorComponent={this.renderSeparator}
      />
    </List>
  );
}

Leaving you with something like this. Notice that at the top and bottom of the list a separator is not rendered.

Header

Rendering a component at the top of the list which scrolls away with the content as you scroll down the list is just as easy as adding the separator. To actually accomplish this you’ll be using the SearchBar component from React Native Elements.

First create a new function that renders the component you want in the header.

FlatListDemo.js

class FlatListDemo extends Component {
  ...

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />;
  };

  ...
}


You then want to actually render that header by using the ListHeaderComponent prop on the FlatList.

FlatListDemo.js

render() {
  return (
    <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
      <FlatList
        ...
        ItemSeparatorComponent={this.renderSeparator}
        ListHeaderComponent={this.renderHeader}
      />
    </List>
  );
}

Leaving you with the following…

Footer

The footer is very much the same as the Header, just that it’s at the end of the list rather than the start. This footer is going to be a bit more complex than the previous example (setting it up for infinite scroll) but the same principles apply. First create a method to call for the footer and return a component.

FlatListDemo.js

render() {
  return (
    <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
      <FlatList
        ...
        ListHeaderComponent={this.renderHeader}
        ListFooterComponent={this.renderFooter}
      />
    </List>
  );
}

Then call that function from ListFooterComponent.

That leaves you with something like this (I’ve adjusted the code a bit to make sure you can see the ActivityIndicator).

Pull to Refresh

Infinite Scroll

Recommended Courses:

React Native: Build Your Own Mobile Apps

http://bit.ly/2jQQH5U

React Native : Build Native Mobile Applications

http://bit.ly/2KTiKy3

React JS - Build real world JS apps & deploy on cloud

http://bit.ly/2JsGWt0

#reactjs #javascript

What is GEEK

Buddha Community

How to Use FlatList | React Native FlatList Tutorial
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

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

How much does it cost to develop a React Native mobile app?

React Native allows developers to develop mobile apps that have compatibility with Android, iOS & other operating systems. Due to the features like Native-like functionality and single code reusability and the access of various frameworks in the market, React Native has excelled as the most suitable framework for cross-platform mobile app development.

Why Do Businesses Prefer React Native App Development?

React Native is integrated with JS library that works as the fundamental for developing the app UI. Most businesses choose for developing React Native apps just due to their cross-platform & open-source features. A few further reasons why entrepreneurs & developers choose React Native app development include:

• Lowered Expedition Time

• Simple UI

• Cross-Platform and Code Sharing

• Lesser Workforce and Resources

• Community Assistance

• In-Built Elements and Reusable Codes

• Hot Reload

• JavaScript as Programming Language

• Easy to Execute Updates

Factors That Decide Cost of React Native App Development

If you are an entrepreneur or start-up and looking for cost-effective app development, React Native is one of the ideal options available out there.

• App’s UI/UX Design

• User Authorization

• App Complexity and Functionality

• App Development Team

• App Maintenance

• App Add-ons

• App Distribution

• Location of Development Company

• App Category

React Native cost depends widely on the complexity of a project or the app requirements. The price may also vary based on business requirements. React Native app development per hour can cost from $20 and $30 per hour in India. It can vary as per different locations.

Is React Native a good choice for mobile apps development?

Yes, React Native is the best choice for mobile app development as React apps are faster to develop and it offers better quality than hybrid apps. Additionally, React Native is a mature cross-platform framework.

Best React Native App Development Agency

AppClues Infotech is a leading React Native App Development Company in USA that build robust & innovative mobile app as per your specific business needs. They have a dedicated team of designers and programmers help to make a perfect mobile app.

If you have any mobile app development project in mind get in touch with AppClues Infotech and get the best solution for your business.

#react native app development cost #react native development company #best react native development company in usa #hire react native developers #hire dedicated react native developers & programmers #hire a react native development company