Search code examples
reactjstextareaarray-splice

How can I delete the correct textarea?


I am trying to delete a textarea at a certain location using splice. When splicing the array, it comes out as expected. But for some reason, the textarea at the end is the textarea that gets deleted and not the textarea that i want to delete.

I have already tried using 2 different arrays but its the same result. I am not sure what else to try.

class App extends Component {

  state = {
    pro : []
  }

  //onclick add a textarea
  onclick = () => {

    let arr = this.state.pro;

    arr = this.state.pro.concat(0);

    this.setState(
      {
        pro : arr
      }
    )

    console.log(arr);
  }

  //change the text content of a textarea at an index

  onchange = (i, e) => {
    let arr = this.state.pro;

    arr[i] = e.target.value;

    this.setState(
      {
        pro : arr
      }
    )
  }

  remove = (i, e) => {
    let arr = this.state.pro
     arr.splice(i, 1)

     this.setState(
      {
          pro: arr
      })
  }

  render() {

    console.log(this.state.pro)

    return (
      <div>

        {this.state.pro.map((con, k) => 
            <div key = {k}>
              <textarea key = {k} onChange = {this.onchange.bind(this, k)}></textarea>
              <button onClick = {this.remove.bind(this, k)}>-</button>
            </div>
        )}

        <button onClick = {this.onclick}>+</button>
      </div>
    );
  }
}

There are no error messages. The expected result would be that the CORRECT textarea deletes when I press the minus button next to it. Not the top each time.


Solution

  • Because your textarea value is not controlled by your state.

    • Set sttribute value in textarea
    • You don't need to bind if you use arrow function
    • key is not necessary to textarea
    return (
                <div>
    
                    {this.state.pro.map((con, k) =>
                        <div key = {k}>
                            <textarea value={con} onChange = {(e) => this.onchange(k, e)}/>
                            <button onClick = {(e) => this.remove(k, e)}>-</button>
                        </div>
                    )}
    
                    <button onClick = {this.onclick}>+</button>
                </div>
            );