What is a Flatlist? How we use Flatlist in react-native

Rather than showing the list of items using the map function on an array and returning some JSX for each item in that array and then embedding that inside a scrollview so we can scroll up and down in that list.
Another way of showing a list that is better to use in any condition is Flatlist. In Flatlist, we don’t need to use scrollview because Flatlist comes with the ability to scroll up and down the list so we will get rid of that instead of importing.

 How to use:

First of all, we need our Flatlist components. We don’t have an opening and a closing tag. Flatlist is a self-closing component. And here we have different numbers of props that control how our list works. So first props are:

1. Data:
Data props specify the data that we want to show. We have to pass data as an array. e.g.

2. Render Item:
This prop is going to be a function. Now this function return some jsx with some item in the array that we are iterating we have to destructure it because it is not just the item
e.g. <Flatlist. renderItem={({item})=>(
return(<Text>{people.name}</Text>)
)} />

3. numColumns:
numColumns props are used to show data in multiple columns.

4. Horizontal:
If this prop is true, then data will be displayed horizontally.

5. KeyExtractor:
It is used to specify the unique value in the given lists of items.

6. ListHeaderComponent:
This prop render at the top of the item

7. ListFooterComponent:
This prop render at the end of the item

8. Refreshing:
Set true while waiting for new data to refresh

Implementation:

import React from "react";
import { StyleSheet, Text, View, FlatList } from "react-native";
const Person = [
  {
    id: "1",
    name: "Alex"
  },
  {
    id: "2",
    name: "Michel"
  },
  {
    id: "3",
    name: "Robert"
  },
  {
    id: "4",
    name: "William"
  },
  {
    id: "5",
    name: "James"
  }
];

const Item = ({ title }) => {
  return (
    <View style={styles.item}>
      <Text>{title}</Text>
    </View>
  );
};

export default function App() {
  const renderItem = ({ item }) => (
    <Item style={styles.text} title={item.name} />
  );
  return (
    <View style={styles.container}>
      <FlatList
        data={Person}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginTop: 30,
    padding: 2
  },
  item: {
    backgroundColor: "green",
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16
  },
  text: {
    color: "red"
  }
});

 Code Output:

code

IMAGE CREDITS: arrowhitech

Let's talk about your tech solutions.

Table of Contents

Get In Touch With Us!

×