0

How do I handle checkbox inside of loop in react native. Currently, my code is like this.

this.state.allItems.map((res, index) => {
 return(
     <CheckBox 
         color="green"
         style={{ marginRight: 20, }}
         checked={this.state.check1}
         onChange={()=>{ }}
/>

)

})
2
  • What's wrong with that code? Does it throw any errors / behave unexpectedly? Commented Jul 17, 2020 at 14:06
  • Try explaining what you'd expect or what you are trying to achieve. Checkboxes can be handled in multiple ways. This probably mostly depends on how you want to store the checked value in the state. Commented Jul 17, 2020 at 14:29

1 Answer 1

1

If I understand your question correctly, you have multiple items and you want them to be independently checkable.

To do that you will need for them to each have their own state value. How you do this will depend on your design needs, but form your code you would need to have an array instead of the check1 state.

Something like this:

this.state.allItems.map((res, index) => {
 return(
     <CheckBox 
         color="green"
         style={{ marginRight: 20, }}
         checked={this.state.checked[index]}
         onChange={()=> {
                  let { checked } = this.state;
                  checked[index] = !checked[index];
                  this.setState({checked});
         }
 }
/>

Of course you will need to populate the checked state properly with an array.

Sign up to request clarification or add additional context in comments.

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.