Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass the React unique key to onChange method

I'm using React ES6. I'm rendering an inventory list containing unique fish elements, each fish element is mapped to a unique key and inherits props from parent component. I'd like to be able to edit the fish text and have this change feed in to the parent state.

My code below doesn't work as the key prop is not available to the onChange handler. Most of the documentation online recommends ReactLink for bi-directional flow but this is now deprecated so I would rather find another solution. My question is two-fold - what is the best pattern for bi-directional flow in ES6 react components and why does this code not work -specifically why can't I console log 'key' in the onChange handler.

Much gratitude

  render () {
    var fishIds = Object.keys(this.props.fishes);
    console.log("fishes are....." +fishIds);
    return (
      <div>
      <h2>Inventory</h2>
      {fishIds.map(this.renderInventory)}
      <AddFishForm {...this.props}/>
      <button onClick={this.props.loadSamples}> Load Sample Fishes</button>
      </div>
    )
  }

Maps Keys and passes them to renderInventory

renderInventory(key) {

      var fish = this.props.fishes[key];
        console.log(fish);
        console.log("the key is" +key);
        var nameOfFish = fish.name
    return(
<div className = "fish-edit" key={key}>
<input type = "text" value ={nameOfFish} onChange={this.handleChange(key)} />
<input type = "text" value ={fish.price}/>


<select>
  <option value = "unavailable">Sold out!  </option>
  <option value = "available">Fresh!  </option>
</select>


<textarea value={fish.desc}>
</textarea>
</div>

    )

  }

HandleChange can't log key

handleChange(event, key){
console.log("the change handler is now firing and the key is" + key);

}
like image 710
ElJefeJames Avatar asked Dec 19 '22 15:12

ElJefeJames


1 Answers

You should wrap your event callback to function or use .bind

<input 
  type="text"
  value={ nameOfFish } 
  onChange={ (e) => this.handleChange(e, key) } 
/>
like image 60
Oleksandr T. Avatar answered Dec 31 '22 02:12

Oleksandr T.