P
P
poniatowski2019-05-05 21:28:00
JavaScript
poniatowski, 2019-05-05 21:28:00

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

2 answer(s)
0
0xD34F, 2019-05-05
@poniatowski

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}
/>

Accordingly, the calculation of the sum will look like this:
const sum = this.state.workers.reduce((acc, n) => acc + (n.checked ? n.salary : 0), 0);

https://codesandbox.io/s/ol342z1znz

A
Anton Spirin, 2019-05-06
@rockon404

Solution option.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question