It is easily the most rage-inducing programmer moment I ever had, mainly because it's so fucking stupid and the only reason it took me so long was because the actual tutorial and documentation was fucking lying to me.
Technically speaking they fixed it by now: they mention the bind-thingy under "Handling Events" in the documentation, which you randomly have to stumble upon:
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
}));
}
However, the tutorial is still deceiving: constructor() {
super();
this.state = {
squares: Array(9).fill(null),
};
}
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
}
This is fine in this specific situation because the render method uses a closure: onClick={() => this.handleClick(i)}
But this is a subtle nuance that can be an incredible pain to figure out. There is no mention of all the this-related pains in the tutorial anywhere.