Since I am pretty new to React and also not a huge expert on JS especially ES6, I wonder how to make my code (that works) prettier and refactor it.
I want to handle multiple checkboxes in a form and store the current value in the state object. Since the checkboxes are grouped I want a structure as answeredTasks like that:
{
"isLoaded":true,
"answeredTasks":{
"1":[
"green",
"blue",
"red"
],
"5":[
"car",
"cat",
"house"
]
}
}
Here is my onChange method on a checkbox:
checkBoxOnChange = e => {
let currentAnswers = this.state.answeredTasks;
let element = e.currentTarget;
// if it is the first answer checked
if (currentAnswers[element.name] === undefined) {
currentAnswers[element.name] = [];
}
// if uncheck
if (!element.checked) {
const index = currentAnswers[element.name].indexOf(element.value);
currentAnswers[element.name].splice(index, 1);
} else {
currentAnswers[element.name].push(element.value);
}
this.setState({ answeredTasks: currentAnswers });
};
Can you tell me how to improve my method, especially with ES6? I mostly struggled with creating the data structure.
Thanks.