I am a newbie to React, and working on a React JS application. I need to make some checkboxes to be checked default based on a set of values in an array. The domain value set is in another array.
Tried to accomplish the task using a nested loop with array.map()
Also, tried to make a callback function within a single loop and tried with array filtering as well. None of them worked correctly:
// Set of possible check box values ( file: person.jsx )
Domain=[
{ id:0, name:"apple", value:"Apple" },
{ id:1, name:"orange", value:"Orange" },
{ id:2, name:"banana", value:"Banana" },
{ id:3, name:"rGrape", value:"Red grapes" },
{ id:4, name:"gGrape", value:"Green grapes" },
]
// a single user's preferences ( file: person.jsx )
state={
userid:0,
name:"Tom",
gender:"Male",
age:20,
fruits:["apple", "rGrape"]
}
The partial code Implemented inside render():
// ( file: person.jsx , inside render() )
{
this.Domain.map(
(fruit, index) => (
//console.log();
<p>
<li key={fruit.id}>
<input type="checkbox"
defaultChecked=
{ //false //if set to false all unchecked
this.state.fruits.map(
(stateFruit) =>(
if(fruit.name === stateFruit)
return true;
else
console.log(false);
console.log(fruit.name === stateFruit)
)
)
}
onChange={this.handleChangeChk} /> {fruit.value}
</li>
</p>
)
)
}
I expected this only checks user selected fruits but it checks every checkbox. It would be great if anybody could suggest a method to accomplish this task, may be with a different approach.