...

/

Scopes in Event Handlers

Scopes in Event Handlers

Learn how to bind class methods to the instance using different binding methods.

Scoping

Usually, the use of ES2015 classes in React mandates that event handlers have to be defined as methods of the current class component. However, class methods are not automatically bound to the instance. Let’s unpack what this means. Initially, this will be undefined in all of our event handlers.

Here is an example to reiterate this:

import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './app.js';
require('./style.css');

ReactDOM.render(
  <Counter />, 
  document.getElementById('root')
);

An onClick event is added to increment the counter by one each time the user presses a button labeled +1. But when the user clicks the button, instead of seeing the actual counter, they will receive the following error message:

Why is that? The answer is scoping! Whenever we click the button in the increase() event handler, we actually operate outside of the component instance. This means we cannot access this.setState(), resulting in our above error. While it might seem annoying, it is not actually something React has thought up, but it’s actually standard behavior for ES2015 classes. But fear not, there are several techniques to combat this:

Method binding in the render()

...