Yan Foto Yan Foto - 4 months ago 14
React JSX Question

React: Retrieve dynamic child key upon event

I am aware that dynamic children of a component must have a unique

key
as the following (modified example from official docs):

render: function() {
var results = this.props.results;
return (
{results.map(function(result) {
return <ChildComponent type="text" key={result.id} changeCallback={this.props.callbackFn}/>;
})}
);
}


Considering that
ChildComponent
is another React component nested here, with a
render
method as bellow

render: function() {
var results = this.props.results;
return (
<div className="something">
<input type="text" onChange={this.props.changeCallback} />
</div>
);
}


is there any way to access the key when
callbackFn(event)
is called?

Answer

Partially apply the function callback by using JavaScript's native bind. This is mentioned in React's "Communicate Between Components" doc:

callbackFn: function(key) {
  // key is "result.id"
  this.props.callbackFn(key);
},
render: function() {
  var results = this.props.results;
  return (
    <div>
      {results.map(function(result) {
        return (
          <ChildComponent type="text" key={result.id}
            changeCallback={this.callbackFn.bind(this, result.id)} />
        );
      }, this)}
    </div>
  );
}