React event handler should have proper this object binding

  • REACT_EVENT_HANDLER_INVALID_THIS
  • Error
  • High
  • react

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

When calling an event handler, React does not provide this object. So, if you try accessing 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 ES6 arrow function.

Note:

  1. createReactClass() automatically binds member functions with this object. So, extra care should be taken when converting it to ES6 class.
  2. 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. (TypeError: Cannot read property 'setState' of undefined)
    }

    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.

See

Was this documentation helpful?