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

4.3k Views Asked by At

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);
}
2

There are 2 best solutions below

9
On BEST ANSWER

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,
}));
0
On

Try to use the select field of Form Builder. https://github.com/bietkul/react-native-form-builder