jsx-eslint / eslint-plugin-react

React-specific linting rules for ESLint
MIT License
8.97k stars 2.77k forks source link

[New Rule]: no-unbound-method #3709

Closed sampattuzzi closed 4 months ago

sampattuzzi commented 6 months ago

This rule already exists in typescript-eslint but isn't detected in the context of JSX.

class MyComponent extends React.Component<{}, {}> {
  render() {
    return <button onClick={this.handleClick}>Click me!</button>;
    //                      ~~~~~~~~~~~~~~~~  passing unbound method
  }

  handleClick(e: any) {
    alert('You clicked!');
  }
}

The rule should warn about this usage and possible duplicated the functionality of the rule in typescript-eslint: https://typescript-eslint.io/rules/unbound-method

ljharb commented 4 months ago

The proper solution here, fwiw, is in the constructor, to do this.handleClick = this.handleClick.bind(this) - or, to do handleClick = this.handleClick.bind(this); as a class field right above the method.

Also, we already have the jsx-no-bind rule.