React native – Flatlist onPress is returning all the dataset not only the one selected

You can use TouchableOpacity for the click event.

Snapshot:

Snapshot

Here is the working example of how you can implement it:

import React, { useState } from 'react';
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import Constants from 'expo-constants';

// You can import from local files

// or any pure javascript modules available in npm

const ingredientList = [
  {
    id: 1,
    name: 'item1',
  },
  {
    id: 2,
    name: 'item 2',
  },
  {
    id: 3,
    name: 'item 3',
  },
  {
    id: 8,
    name: 'item 4',
  },
  {
    id: 4,
    name: 'item 5',
  },
  {
    id: 5,
    name: 'item 6',
  },
];

export default function App() {
  const [selectedItem, setSelectedItem] = useState(null);
  const selectedIngredient = (item) => {
    console.log('selecionado: ' + item.name);
    setSelectedItem(item);
  };
  return (
    <View style={styles.container}>
      <FlatList
        style={styles.flatlist}
        horizontal
        bounces={false}
        key={ingredientList.id}
        data={ingredientList}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={styles.flatListItem}
            key={item.id}
            onPress={() => selectedIngredient(item)}>
            <Text>{item.name}</Text>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.index}
      />

      {selectedItem ? (
        <View style={styles.selectedTextView}>
          <Text style={styles.selectedText}>{`${selectedItem.name} selected`}</Text>
        </View>
      ) : (
        <View style={styles.selectedTextView}>
          <Text style={styles.selectedText}>{`Nothing selected`}</Text>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  flatListItem: {
    width: 100,
    height: 100,
    backgroundColor: 'white',
    margin: 5,
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selectedTextView: {
    flex: 1,
    backgroundColor: 'white',
    margin: 5,
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
    fontSize: 20
  },
  selectedText: {
    fontSize: 30
  },
});

Working Demo: Expo Snack

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top