0

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 Answers 2

2

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,
}));
Sign up to request clarification or add additional context in comments.

9 Comments

I'm sorry but I got selectedItems undefined and setState is not a function.
checked={rowData.id === this.state.checkedBoxCheck} what is it? You have array in state, you can not make a comparison this way.
[{row}] it is [ { row: row } ] but I do not understand why you are doing this
Sorry, I thought this line --- checked={rowData.id === this.state.checkedBoxCheck} causes the problem why the checked box is not showing I forgot to delete that,
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.