In JavaScript, class methods are not bound to class instances by default. In React, that means using either .bind()
or an arrow function onClick={(e) => this.handleClick(e)}
to pass this
.
Alternately, use Class properties. From the React documentation:
class LoggingButton extends React.Component {
handleClick = () => {
console.log('this is:', this);
}
}
This syntax ensures that handleClick
has the correct this
value when called.
In some cases, properties remove the need for constructors in a class. See an example of how this works in an article by Dale Jefferson.
Originally prompted by reading Mapbox React examples code.