Reputation: 2653
I'm trying to call a function while passing the index in. However, I read that it's not best practice to pass a lambda into the onclick handler. Is there a better way of handling this? Because right now isn't a function being created everytime?
Removing the lambda I run the risk of updating the state during a transition which causes infinite calls to the function.
class MyComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.myFunc= this.myFunc.bind(this);
}
myFunc(index){
//do stuff with the index
}
render(){
const items = this.props.list.map((listItem, index) =>
return <div key={listItem.id} onClick={() => this.myFunc(index)}>{listItem.name}</div>
);
return(
<div>{items}</div>
)
}
}
Upvotes: 1
Views: 2265
Reputation: 16441
It is recommended in the React Docs to use bind
to pass additional params:
myFunc(index, e){
// Do something with index...
}
render() {
const items = this.props.list.map((listItem, index) =>
return <div key={listItem.id} onClick={this.myFunc.bind(this, index)}>{listItem.name}</div>
);
return ...
}
Upvotes: 1
Reputation: 4141
The best way to do it is to extract the list item into a new component:
class ListItem extends React.PureComponent{
const myFunc = () => {
const { index } = this.props
// do something with index
}
render(){
const { listItem } = this.props
return (
<div key={listItem.id} onClick={this.myFunc}>{listItem.name}</div>
)
}
}
Upvotes: 3