user944513
user944513

Reputation: 12729

How to set/update clicked item in React.js?

Could you please tell me how to how to set/update a clicked item in React.js?. I want the value of the clicked element to change to "test". How can I setup such event handler to do this?

Here is my code

On item click I am trying to update the item like that

   btnClick(obj) {
        obj.hse = 'test';
        console.log(obj);
        // this.setState({
        //     data: [obj]
        // });
    }

Upvotes: 0

Views: 411

Answers (1)

Chris
Chris

Reputation: 59501

Since your data object is an array, I think the easiest way to implement this is to send your btnClick() function the id of the element that was clicked, update that value, and then save the new state.

Codepen

Like so:

this.state.data.map((item, i) => {
  return <li onClick = {
    this.btnClick.bind(this, i)
  > {
     item.hse
  } < /li>;
})

By changing map(item) => { to map(item, i) => { you make use of the index parameter of the Array map method. This i variable is then used when binding the btnClick function.

btnClick(id) {
    let temp = this.state.data.slice();
    temp[id].hse = 'test';
    this.setState({
      data: temp
    });
}

Here, the id is the index of the item clicked. Start off by creating a shallow copy of the this.state.data and put it into a local temp variable. Then, change the hse property of temp[id]. Finally, update the data state with the local variable.

edit: fixed broken codepen link

Upvotes: 1

Related Questions