I'm aware theres similar threads that discuss the scoping issue.
Using the following component
import React from 'react';
import ReactDOM from 'react-dom';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
addMore() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
return (
<div onClick={ this.addMore }>
<p>counter: { this.state.counter }</p>
</div>
);
}
}
if (document.getElementById('example')) {
ReactDOM.render(<Example />, document.getElementById('example'));
}
When you click the div
you get Cannot read property 'setState' of null
I'm aware you can do things like this.addMore.bind(this)
but all this seems weird extra boilerplate style code just to make it work.
What is considered the most elegant way to do this? As surely people must have a preferred way which have their benefits, other than being an eye sore?