React event handlers accessing this object should have proper this binding

  • REACT_EVENT_HANDLER_INVALID_THIS
  • Error
  • High
  • react

This rule applies when a function accessing this object is used as a React event handler without this binding.

When calling an event handler, React does not provide this object. So, if you try to access a property of this inside the handler, a TypeError exception is thrown.

To fix this problem, you can use Function.prototype.bind() to specify this object or use an arrow function.

Note: This rule may report false alarms when an unconventional automatic binding mechanism is used. We recommend disabling this rule in such cases.

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';

export class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "John" };
  }

  handleClick() {
    this.setState({ name: "Mary" }); // 'this' has undefined value and TypeError is thrown.
  }

  render() {
    return (
      <div onClick={this.handleClick}> {/* REACT_EVENT_HANDLER_INVALID_THIS alarm because 'this.handleClick' function is not bound with 'this'. */}
        {this.state.name}
      </div>
    );
  }
}

Compliant Code Example

View with noncompliant examples side by side
import React from 'react';

export class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "John" };

    // Bind event handler inside constructor
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ name: "Mary" });
  }

  render() {
    return (
      <div onClick={this.handleClick}>
        {this.state.name}
      </div>
    );
  }
}

Version

This rule was introduced in DeepScan 1.3.0-beta.

Was this documentation helpful?