3 ms·
Having .bind inside a JSX prop also creates a new anonymous function on each render. To avoid it, you can do (sorry for bad formatting): class Thing extends
by alxlu 8y ago
Having .bind inside a JSX prop also creates a new anonymous function on each render.
To avoid it, you can do (sorry for bad formatting):
class Thing extends React.Component {
handleClick = (thingId) => {
this.setState(/*stuff*/);
}
render() {
return <div>{things.map(thing => <Thing onClick=
{this.handleClick} />)}</div>
}
}
You can also bind handleClick inside the constructor without the arrow.
constructor(...args) {
super(...args);
this.handleClick = this._handleClick.bind(this);
}
_handleClick(thing) {
// stuff
}
- mercer 8y agoThe latter version seems to be the one I most commonly see, except _handleClick() is just handleClick() repeated. Am I correct in assuming this is considered idiomatic at this point?
- antonkm 8y agoYes, I'd say so.
- mercer 8y agoIs this better somehow? I feel like I should know this, but it's Friday night and I'm tired, but isn't the constructor fired on every instance of the component? And if so, is this a better approach for any particular reason other than clarity?
- aenigmaclamo 8y agoIt is fired on every instance of the component. However, if you create the arrow function in the render function, it'll be created for every render. Since React keeps the component instances around between renders, it can be a lot better.
- mercer 8y agoAh, that makes sense. Do you by any chance know of any articles that go further into how this works?
- RunawayGalaxy 8y agohttps://pbs.twimg.com/media/DZ-97vzW4AAbcZj.jpg:large https://pbs.twimg.com/media/DZ-97vzW4AAbcZj.jpg:large
- mercer 8y agoPerfect!