Home > Net >  How to select multiple checkboxes in 'Flatlist'?
How to select multiple checkboxes in 'Flatlist'?

Time:04-21

I'm working on flatlist with checkbox but could not select multiple checkboxes inside flatlist. Every time only single item is selected. Wanted to add dynamic checkbox according to the list and have to handle all checkbox using one function. I have used the following code but its not working. Any help would be appreciated.

import React, { useState, useEffect } from 'react';                                                                              
    import {
      SafeAreaView,
      StyleSheet,
      Text,
      View,
      FlatList,
      TouchableOpacity,
      Image,
      ActivityIndicator,
    } from 'react-native';
    import CheckBox from '@react-native-community/checkbox';
    
    
    const App = () => {
    
      const [isLoading, setIsLoading] = useState(true);
      const [data, setData] = useState([]);
    
      useEffect(() => {
        getListPhotos();
        return () => {
        }
      }, [])
    
      getListPhotos = () => {
        const apiUrl = 'https://jsonplaceholder.typicode.com/photos';
        fetch(apiUrl)
          .then((res) => res.json())
          .then((resJson) => {
            setData(resJson);
          }).catch((err) => { console.error('Error', err); })
          .finally(() => setIsLoading(false))
      }
    
    
      onChangeValue = (item, index) => {
        const newData = data.map(newItem => {
          if (newItem.id == item.id) {
            return {
              ...newItem,
              selected: true,
            }
          }
          return {
            ...newItem,
            selected: false,
          }
        })
        setData(newData);
      }
    
      renderItem = ({ item, index }) => {
        return (
          <View style={styles.item}>
            <Image style={styles.image}
              source={{ uri: item.url }}
              resizeMode='contain'
            />
            <View style={styles.wrapText}>
              <Text >{item.title}</Text>
              <CheckBox
                value={item.selected}
                style={styles.ckItem}
                disabled={false}
                onAnimationType='fill'
                offAnimationType='fade'
                boxType='square'
                onValueChange={() => onChangeValue(item, index)}
              />
            </View>
          </View>
        )
      }
      
      return (
        <SafeAreaView style={styles.container}>
          {isLoading ? <ActivityIndicator /> : (<FlatList
            style={styles.list}
            data={data}
            renderItem={renderItem}
            //keyExtractor={(item, index) => item.id}
             keyExtractor={item => `key-${item.id}`}
          />)}
          <View>
            <Text style={styles.wrapButton}></Text>
            <TouchableOpacity style={styles.button}>
              <Text>
                Show item you selected
              </Text>
            </TouchableOpacity>
          </View>
        </SafeAreaView>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      list: {
        flex: 1,
        padding: 8,
      },
      wrapButton: {
        width: '100%',
        justifyContent: 'center',
        alignItems: 'center',
      },
      button: {
        padding: 16,
        backgroundColor: 'orange',
        // justifyContent:'center',
        // alignItems:'center',
        alignSelf: 'center',
        width: '50%'
      },
      item: {
        marginTop: 8,
        flexDirection: 'row',
        padding: 4,
        shadowColor: '#000',
        shadowOffset: {
          width: 0, height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
      },
      image: {
        width: 100,
        height: 150,
      },
      wrapText: {
        flex: 1,
        marginTop: 16,
        marginLeft: 8,
      },
      ckItem: {
        width: 20,
        height: 20,
        marginTop: 5,
    
      },
    });
    
    export default App;

CodePudding user response:

onValueChange={newValue => onChangeValue(item, index, newValue)}

onChangeValue = (item, index, newValue) => {
    const newData = data.map(newItem => {
      if (newItem.id == item.id) {
        return {
          ...newItem,
          selected: newValue,
        }
      }
      return newItem
    })
    setData(newData);
  }

CodePudding user response:

You can achieve by using below plugins

https://bestofreactjs.com/repo/tableflip-react-native-select-multiple-react-react-native-awesome-components

https://github.com/vakiller/react-native-flatlist-multiple-choose/blob/master/readme.md

  • Related