Search code examples
checkboxreact-nativereact-native-listview

How to select mulitple items with listview using checkbox in react native?


I'm working on listview with checkbox. I'm trying to select multiple items but I discovered something in the result that every time I click the checkbox the result is replacing the first item that I checked

here's my case:

    this.state = {
     ...
     checkedBoxCheck: false,
     selectedItems:[],
   };

    renderRow(rowData) {
        return (
            ...
           <CheckBox style={styles.checkboxed}
              checked={rowData.id === this.state.checkedBoxCheck}
              onPress={() => this.onItemSelect(rowData)}
            />
        );

onItemSelect(row){
    this.setState({
        selectedItems: [{row}],
        checkedBoxCheck: true,
    });
    let myitem = this.state.selectedItems.concat({row});
    console.log(myitem);
}

Solution

  • You forgot to write in the state the previous values selectedItems:

    this.setState((prevState) => ({
        selectedItems: [...prevState.selectedItems, row],
        checkedBoxCheck: true,
    }));
    

    And deleting value (with lodash):

    this.setState((prevState) => ({
        selectedItems: _.without(prevState.selectedItems, row),
        checkedBoxCheck: !!_.without(prevState.selectedItems, row).length,
    }));