React Native Flatlist Onpress Item Event Example

Sep 08, 2022 . Admin

In this tutorial, you will learn react native FlatList example. let’s discuss about Example of Get FlatList Selected Clicked Item in React Native. step by step explain react native flatlist onpress item. In this article, we will implement a react native flatlist onpress.

In this example, we would learn about getting clicked Item from a FlatList in react native and show the selected item on screen using Alert.let's below example.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React from 'react';
import { Alert, View, StyleSheet, SafeAreaView, FlatList, Text } from 'react-native';
 
export default function App() {
 
  const Countries  = [
    {
      id: 1,
      name: 'India',
    },
    {
      id: 2,
      name: 'Australia',
    },
    {
      id: 3,
      name: 'Bangladesh',
    },
    {
      id: 4,
      name: 'Brazil',
    },
    {
      id: 5,
      name: 'Canada',
    },
    {
      id: 6,
      name: 'China',
    },
    {
      id: 7,
      name: 'France',
    },
    {
      id: 8,
      name: 'Japan',
    },
    {
      id: 9,
      name: 'Kenya',
    },
    {
      id: 10,
      name: 'Malaysia',
    }
  ];
 
  const getItem = (name) => {
 
    Alert.alert(name);
 
  }
 
  const ItemRender = ({ name }) => (
    <View style={styleSheet.item}>
      <Text style={styleSheet.itemText} onPress={()=> getItem(name)}>{name}</Text>
    </View>
  );
 
  const ItemDivider = () => {
    return (
      <View
        style={{
          height: 1,
          width: "100%",
          backgroundColor: "#607D8B",
        }}
      />
    );
  }
 
  return (
    <SafeAreaView style={styleSheet.MainContainer}>
 
      <FlatList
        data={Countries}
        renderItem={({ item }) => <ItemRender name={item.name} />}
        keyExtractor={item => item.id}
        ItemSeparatorComponent={ItemDivider}
      />
 
    </SafeAreaView>
  );
}
 
const styleSheet = StyleSheet.create({
 
  MainContainer: {
    flex: 1,
    backgroundColor: 'white',
    paddingTop: 35,
  },
 
  item: {
    paddingLeft: 15,
    paddingTop: 8,
    paddingBottom: 8
  },
 
  itemText: {
    fontSize: 24,
    color: 'black'
  }
 
});
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native