Answer the question
In order to leave comments, you need to log in
Correct removal of an array element through input onChange how to do it?
Hello, I think that the purpose of the code task is clear. I would like to see the sums in the table for each marked input. Please tell me where is my mistake? At first glance, the code works, but if we are talking about the last input, then it is not removed from the array. I suspect it has to do with splice.
https://codesandbox.io/s/7zqmjrnjw1
Answer the question
In order to leave comments, you need to log in
Why a separate array? Store the state of checkboxes in workers elements.
When the state of the checkboxes changes, update the workers:
inputChange = e => {
const index = +e.target.dataset.index;
this.setState({
workers: this.state.workers.map((n, i) => i === index
? { ...n, checked: e.target.checked }
: n
),
});
}
<input
type="checkbox"
data-index={index}
onChange={this.inputChange}
checked={item.checked}
/>
const sum = this.state.workers.reduce((acc, n) => acc + (n.checked ? n.salary : 0), 0);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question