In this example here, we need to bind the 'this' object of handleClick() to the global scope:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
However, handleClick() is defined in the scope of the component, so shouldn't we not need to specify the 'this' object for this function, as it will already refer to the component itself?