Hi Guys, In this article we are going to implement React Native Multi Selection. In mobile application user need to select multiple items from list. This tutorial guide you to Implementing Multiple Selection in React Native FlatList. We’ll use React hooks for state management and create a reusable list item component to handle selection logic. This logic will directly update value in react hooks so that it will not take time while selecting data from thousands of list item.
let’s understand with an example.
1. Data Structure and State Management
Let’s define data structure and state management with FlatList component
import React, { useState } from 'react'; import { View, FlatList, Text } from 'react-native'; import ContactListViewItem from './ContactListViewItem'; // Assuming this component is in a separate file const initialData = [ { email: '', firstName: 'Samsung Helpline', id: 1, isSelected: true, lastName: '', otherPhone: '', phone: '1800407267864', salutationId: null, }, // Add more items as needed ]; const App = () => { const [checkedItems, setCheckedItems] = useState([]); // Array to store IDs of selected items const [uncheckedItems, setUncheckedItems] = useState([]); // Array to store IDs of unselected items const [getSelectedData, setSelectedData] = useState([]); // Array to store selected item objects // Function to handle click event on an item const onClick = (item) => { const updatedData = [...getSelectedData]; if (!updatedData.some(selectedItem => selectedItem.id === item.id)) { updatedData.push(item); } setSelectedData(updatedData); }; return ( <View style={{ flex: 1 }}> <FlatList data={initialData} renderItem={({ item, index }) => ( <ContactListViewItem item={item} index={index} onClick={() => onClick(item)} checkedItems={checkedItems} setCheckedItems={setCheckedItems} removedCheckedItems={uncheckedItems} setRemovedCheckedItems={setUncheckedItems} /> )} keyExtractor={item => item.id.toString()} /> {/* Additional UI or controls can be added here */} </View> ); }; export default App;
2. ContactListViewItem.js
This component will handle visual representation and selection logic for each item for FlatList component
import React, { useState, useEffect } from 'react'; import { View, Text, TouchableOpacity } from 'react-native'; import Ionicons from 'react-native-vector-icons/MaterialCommunityIcons'; import COLORS from '../assets/colors/Colors'; import CssSheet from '../assets/Css/CssSheet'; const ContactListViewItem = ({ item, onClick, checkedItems, setCheckedItems, removedCheckedItems, setRemovedCheckedItems, }) => { const [checked, setChecked] = useState(false); useEffect(() => { //setChecked(item.isSelected); }, [item.isSelected]); const updateTaskCall = () => { const isChecked = !checked; setChecked(isChecked); if (isChecked) { // If the item is checked, add its id to checkedItems and remove it from removedCheckedItems setCheckedItems(prevCheckedItems => [ ...prevCheckedItems, item.id, ]); setRemovedCheckedItems(prevRemovedItems => prevRemovedItems.filter(prevId => prevId !== item.id), ); } else { // If the item is unchecked, add its id to removedCheckedItems and remove it from checkedItems setRemovedCheckedItems(prevRemovedItems => [ ...prevRemovedItems, item.id, ]); setCheckedItems(prevCheckedItems => prevCheckedItems.filter(prevId => prevId !== item.id), ); } }; return ( <View style={{ marginHorizontal: 16, backgroundColor: COLORS.white, marginBottom: 4, paddingVertical: 10, minHeight: 56, borderRadius: CssSheet.borderRadius, borderColor: checked ? COLORS.primaryColor : COLORS.white, borderWidth: checked ? 0.5 : 0, justifyContent: 'center', }} > <View style={{ flexDirection: 'row', alignItems: 'center' }}> <TouchableOpacity activeOpacity={0.8} style={{ paddingVertical: 5, paddingRight: 5 }} onPress={updateTaskCall} > <Ionicons name={checked ? 'checkbox-marked' : 'checkbox-blank-outline'} size={24} color={checked ? COLORS.primaryColor : 'grey'} style={{ marginLeft: 12 }} /> </TouchableOpacity> <View style={{ flex: 1 }}> <Text numberOfLines={1} style={[ CssSheet.baseTextMediumStyle, { color: COLORS.defaultText, alignItems: 'center', fontSize: 16, marginHorizontal: 5, }, ]} > {item.firstName} </Text> <View style={{ flexDirection: 'row' }}> <Text style={[ CssSheet.baseTextRegularStyle, { color: COLORS.defaultText, alignItems: 'center', fontSize: 12, marginHorizontal: 5, }, ]} > {item.phone} </Text> </View> </View> </View> </View> ); }; export default ContactListViewItem;
- State Management: We use useState to manage the checked state for each item in ContactListViewItem.
- Effect Hook: The useEffect hook is used to synchronize the checked state with item.selected when the component mounts or item.selected changes.
- updateTaskCall Function: Handles the toggle of checked state and manages the addition or removal of item IDs from checkItems and removedcheckItems arrays based on the isChecked value.
3. Output
Note: I use above selection logic in my one of the project. here’s the visual for Implementing Multiple Selection in React Native FlatList.