Skip to content

Instantly share code, notes, and snippets.

@ihgrant
Last active September 8, 2016 15:43
Show Gist options
  • Save ihgrant/bd20cb106bd1e5733cdf00871ddfe01f to your computer and use it in GitHub Desktop.
Save ihgrant/bd20cb106bd1e5733cdf00871ddfe01f to your computer and use it in GitHub Desktop.
ReactJS: Avoid binding to event handlers with composition
class Example extends React.Component {
onClick(e, id) {
...
}
render() {
return <ul>{this.props.items.map((el, i) => <li onClick={this.onClick.bind(this, el.id)}>{el.description}</li>)</ul>
}
}
/// OR........
class Example extends React.Component {
onClick(e, id) {
...
}
render() {
return <ul>{this.props.items.map((el, i) => <ListItem {...el} onClick={this.onClick}>)</ul>
}
}
class ListItem extends React.Component {
onClick(e) {
this.props.onClick(e, this.props.id);
}
render() {
return <li onClick={this.onClick}>{this.props.description}</li>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment