0

Showing list of checkboxes and I have to show checkbox status based on array data onload

reference code

AllGroups      = [{id:1, name:one},{id:2,name:two},{id:3, name:three},{id:4,name:four}]
userCatChecked = [{id:2,name:two},{id:3, name:three}]

Checkbox status should show true/false based on userCatChecked array matching

<form>
{this.state.AllGroups((item, index) => {

      //  Here need condition 
      // if( item.id === userCatChecked.id  ) {
      // show true checkbox
      //}else{
      // show false checkbox
      //}


   <input type="checkbox" checked={true/false} onChange={ } />
})}
</form>
2
  • AllGroups is Array, you can't call it Commented Mar 19, 2020 at 7:00
  • Didnt understand , code is for just reference Commented Mar 19, 2020 at 7:03

3 Answers 3

1
<form>
    {this.state.AllGroups.map((item, index) => 
       <input
           type="checkbox"
           checked={!!this.state.userCatChecked.find(cat => cat.id === item.id)}
           onChange={ }
       />
    )}
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

working fine but , but checkbox status not changing when i click
You should provide an onChange function
1

How about this?

You can use Array.some function to check if the object array contains an item.

const AllGroups      = [{id:1, name:'one'},{id:2,name:'two'},{id:3, name:'three'},{id:4,name:'four'}]
const userCatChecked = [{id:2,name:'two'},{id:3, name:'three'}]

const result = AllGroups.map((item, index) => {
  const checked = userCatChecked.some(checked => checked.id === item.id);
  return {...item, checked};
});
console.log('result:', result);

So

{this.state.options.AllGroup((item, index) => {
  const checked = userCatChecked.some(checked => checked.id === item.id);
  return <input type="checkbox" checked={checked} onChange={} />;
})}

1 Comment

I didnt try this , I tested with below answer thats worked well , thanks for your help
0

One another way to handle checkboxes is through Map

const userCatChecked = [{id:2,name:'two'},{id:3, name:'three'}];
const checkedItems = new Map();
userCatChecked.map(data => checkedItems.set(data.name, true))

And then in your form

<form>
    {this.state.AllGroups.map((item, index) => 
       <input
           type="checkbox"
           checked={checkedItems.get(item.name)}
           onChange={ }
       />
    )}
</form>

May be this will also help :)

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.