Event handler of a React element should not be a string

  • REACT_BAD_EVENT_HANDLER
  • Error
  • High
  • react

This rule applies when the event handler of a React element is specified with a string.

Unlike HTML, an event handler should be always a function in React. If you specify handler code as a string, React will throw an exception.

Noncompliant Code Example

import React from 'react';

class Hello extends React.Component {
    render() {
        return (
            <div onClick="console.log('clicked')"> {/* REACT_BAD_EVENT_HANDLER alarm */}
                Hello
            </div>
        );
    }
}

Compliant Code Example

import React from 'react';

class Hello extends React.Component {
    handleClick() {
        console.log('clicked');
    }

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

Version

This rule was introduced in DeepScan 1.2.0-alpha.

See

  • Handling Events

  • React Error: Expected onClick listener to be a function, instead got type string