How to bind React component event handlers in ES6
When creating React components using ES6 class notation, you'll need to bind
event handlers passed as props to this
, or you'll find that the handlers will
be bound instead to the DOM element.
There are a few ways to do this. You can reassign the bound handler in the constructor:
class MyComponent extends React.Component {
render() {
return (
<div>
<button onClick={this.onClick.bind(this)}>Click Me</button>
</div>
);
}
onClick(event) {
alert("You clicked me!");
}
}
This works fine, but now you have .bind(this)
littering your otherwise
elegant JSX.
To remedy that, you can use the fat arrow prototype method syntax:
class MyComponent extends React.Component {
render() {
return (
<div>
<button onClick={this.onClick.bind(this)}>Click Me</button>
</div>
);
}
onClick = (event) => {
alert("You clicked me!");
}
}
Except... now you have two separate syntaxes for declaring methods, which could make your code less readable and more confusing.
I think the most elegant way is to use the new double-colon (::
) notation,
which is a shortcut for calling .bind(this)
on a given handler:
class MyComponent extends React.Component {
render() {
return (
<div>
<button onClick={::this.onClick}>Click Me</button>
</div>
);
}
onClick(event) {
alert("You clicked me!");
}
}
Now your caller is binding the method to this
without an ugly .bind(this)
call, and the method body isn't unnecessarily decorated with fat arrow notation.