React: "this" is undefined inside a component function
Solution 1:
ES6 React.Component
doesn't auto bind methods to itself. You need to bind them yourself in constructor
. Like this:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
Solution 2:
There are a couple of ways.
One is to add
this.onToggleLoop = this.onToggleLoop.bind(this);
in the constructor.
Another is arrow functions
onToggleLoop = (event) => {...}
.
And then there is onClick={this.onToggleLoop.bind(this)}
.
Solution 3:
Write your function this way:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
Fat Arrow Functions
the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).