grgre grgre - 3 months ago 12
jQuery Question

Edit text value in React array using props and state?

In trying to learn React, I’m confused on how to handle this situation. Bare in mind I’m still kinda new to scripting languages.

I want to be able to click ‘edit’ and have a text box show up where the ‘name’ is next to the edit button and then proceed to edit the text. I cannot figure out how to get the value of the text I’m clicking on though. I know how to do it with a for loop but I’m trying to do with the ‘react way’ (using props and state). Is that doable?

handleEdit: function(e){
e.preventDefault();
var i = e.target.value; //index in the array
var friendsCopy = this.state.friendsArray;
console.log('SPACE.');
console.log(/*the text of the value in the array*/);
}


Everything I've tried has returned
undefined
or nothing at all (an empty line).
I've tried using
data-
attributes, referring directly to the value (
friendsCopy[e.text]
) and other ways. I know I'm not getting something and I've read the documentation but I can't seem to put it together.

https://jsfiddle.net/nckdls/69z2wepo/54502/

Answer

Modified JS Fiddle: https://jsfiddle.net/wfn0eqtk/

Generally your code was correct, the missing piece was providing the index of the friend that was being edited. Since you already had a ShowList component, I just modified it to bind the click callback with the index of the item being edited, and triggering that to the passed in prop.

triggerEdit: function(index, e) {
    this.props.handleEdit(index, e)
},

<button onClick={this.triggerEdit.bind(this, index)}>

Finally, I modified your handleEdit function in the parent component to accept the new index parameter, access the friendsCopy array, and console.log the result.

handleEdit: function(editingIndex, e){
    var friendsCopy = this.state.friendsArray;
    var editingFriend = friendsCopy[editingIndex];
    console.log(editingFriend);
},

Bind Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Bind is used to change the scope (the value of this) to a function, but it can also be used to pass additional parameters. In this case the parameters are injected before other arguments are passed to the bound function.