Adding and deleting array of classes error

Tags: ,



Below is my attempt to create an array of classes. The functionality of app is next: one can add or delete extra Input box and increase or decrease its value. As a result the app displays the sum of the all present tags. The issue comes with Delete function, when deleting any of components from created list it does correct math in array but rerenders the elements incorrectly. It always deletes the last component on the list even when you try to remove any others. Any hint why it’s happening? Thanks

class Trade1 extends React.Component {
  state = {
    vl: this.props.value
  }
  change = (v) => {
    let newValue
    if (v) {
      newValue = this.state.vl + 1
    } else {
      newValue = this.state.vl - 1
    }
    this.setState({vl: newValue})
    this.props.onChange(newValue, this.props.index)
  }

  render() {
    const {value, index} = this.props
    return (
      <div>
      <button onClick={() => this.change(false)}>Down</button>
      <input class="v_price" value={`${this.state.vl}`}/>
      <button onClick={() => this.change(true)}>Up</button>
      <button onClick={() => this.props.delete(this.props.index)}>Delete</button>
      </div>
    )
  }
}

class Parent  extends React.Component {
  constructor(props){
  super(props);
  this.state = {
    arr: [0,0,0]
  }
 }

  onChange = (v, i) => {
    let newArr = this.state.arr
    newArr[i] = v
    this.setState(newArr)
  }

  plus = () => {
    let a = this.state.arr
    a.push(0)
    this.setState({arr: a})
  }

  minus = i => {
    let a = this.state.arr
    a.splice(i, 1)
    console.log(a)
    this.setState({arr: a})

  }

  render() {
    return (
      <div>
      {this.state.arr.map((v, i) =>
        {
            return <Trade1 value={v} index={i} onChange={this.onChange} delete={this.minus}/>
        }
      )}
      <div>{
        this.state.arr.reduce((a, b) => a+b, 0 )
      }</div>
      <div><button onClick={this.plus}>Plus</button></div>
      </div>
    )
  }
}



ReactDOM.render(<Parent />, document.getElementById('root'));

Answer

You are mutating the array, you should use filter and remove the element at index which you pass as an argument

  minus = i => {
    this.setState({
      arr: this.state.arr.filter((x, j) => j !== i)
    })
  }


Source: stackoverflow