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: React.createClass() automatically binds member functions with this object. So, extra care should be taken when converting it to ES6 class.

Noncompliant Code Example

import React from 'react';

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 null)
    }

    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

import React from 'react';

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