Hunter
Hunter

Reputation: 1601

React js map and filter

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>

Upvotes: 0

Views: 66

Answers (3)

Qubaish Bhatti
Qubaish Bhatti

Reputation: 728

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 :)

Upvotes: 0

Diamond
Diamond

Reputation: 3428

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={} />;
})}

Upvotes: 1

Burak Gavas
Burak Gavas

Reputation: 1354

<form>
    {this.state.AllGroups.map((item, index) => 
       <input
           type="checkbox"
           checked={!!this.state.userCatChecked.find(cat => cat.id === item.id)}
           onChange={ }
       />
    )}
</form>

Upvotes: 1

Related Questions