Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  9] [ 6]  / answers: 1 / hits: 22965  / 10 Years ago, sat, may 3, 2014, 12:00:00

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?


More From » reactjs

 Answers
4

Although the first answer is correct this is considered as a bad practice since:




A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.




Better way:



var List = React.createClass({
handleClick (id) {
console.log('yaaay the item key was: ', id)
}

render() {
return (
<ul>
{this.props.items.map(item =>
<ListItem key={item.id} item={item} onItemClick={this.handleClick} />
)}
</ul>
);
}
});

var ListItem = React.createClass({
render() {
return (
<li onClick={this._onClick}>
...
</li>
);
},
_onClick() {
this.props.onItemClick(this.props.item.id);
}
});


Source: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md


[#71198] Wednesday, April 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ibrahimr

Total Points: 468
Total Questions: 99
Total Answers: 93

Location: Serbia
Member since Sun, Jul 11, 2021
3 Years ago
;