React Autobinding Fix 4
Fiddles about the best way to bind event handlers in React
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
class MyComponent extends React.Component {
state = {
clickCount: 0
}
constructor(props) {
super(props);
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount() {
this.setState({
clickCount: this.state.clickCount + 1
});
}
render() {
return (
<div>
<button onClick={this.incrementCount}>
Click Me!
</button>
<div>
<p>{`Total amount of clicks: ${this.state.clickCount}`}</p>
</div>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('container')
);