I am working on this project where my requirement is to create dynamic checkboxes on the fly on runtime. I get values in array from API in componentWillMount and the array looks like this:
["Diesel", "SomeTeam", "demo", "lazyTeam", "demoTeam", "X & G", "Kteam"]
I have been breaking my head over this to solve this and so far I've been creating dynamic states in componentWillMount to mark all checkboxes initially False and the component I am rendering the checkboxes by parsing the array with map function.
componentWillMount looks like this:
axios.get(`/teams/tlist`).then(response => {
let tempTeamArr = []
Object.keys(response.data.teams).map((key, index) => {
tempTeamArr.push(response.data.teams[key].name)
console.log(tempTeamArr)
if(index == Object.keys(response.data.teams).length-1) {
this.setState({
allTeams: tempTeamArr,
[`${response.data.teams[key].name}CheckedStat`]: false
}, () => {
console.log(`dynamic state: this.state[${response.data.teams[key].name}CheckedStat]`, this.state[`${response.data.teams[key].name}CheckedStat`])
})
}
})
})
and my checkbox component looks like this:
{allTeams.map((data, index) => {
return (
<Checkbox
label={data}
id={data}
checked={this.state[`${data}CheckedStat`]}
onChecked={bool => {this.setState({[`${data}CheckedStat`]: !this.state[`${data}CheckedStat`]})}}
/>
)})
Checkbox component code is:
const Checkbox = ({ label, id, onChecked, checked }) => (
<StyledCheckbox>
<input
className="checkbox"
type="checkbox"
id={id}
value={id}
onChange={e => onChecked(e.target.checked)}
checked={checked}
/>
<label htmlFor={id}>{label}</label>
</StyledCheckbox>
)
export { Checkbox }
Problem I am facing is, this renders checkboxes but the check uncheck is very erratic and out of control. I need your help real bad and would be really greatful if you could help me solve this. This will help more people like me who are stuck on such trivial UI rendering issue yet complex problem.
Thank you.
allTeams: tempTeamArrevery iteration?