Solvedjavascript react/jsx-no-bind: how to pass args from callbacks?

I have a question about react/jsx-no-bind rule in 3.0.0: how can I pass args to handler from callback if I can't use bind and arrow functions?

doSomething(thing) { ... }

render() {
  const { items } = this.props;

  return (
    <ul>
    {
      items.map(item => (
        <li onClick={this.doSomething.bind(this, item)} /> // <--- JSX props should not use .bind()
        <li onClick={() => this.doSomething(item)} />      // <--- JSX props should not use arrow functions
      ))
    }
    </ul>
  );
}
57 Answers

✔️Accepted Answer

Right - at that point you might as well disable the rule.

Other Answers:

There are some tips in the eslint-plugin-react#jsx-no-bind documentation.

tl;dr, you can create another React component for the list items where you pass in the item and the click handler and pass the item as a param.

What do you think of this approach? Each function is created once in the constructor and that is it.

class Form extends React.Component {
  constructor() {
    const fields = this.props.fields;

    this.changeField = {};
    this.fields.forEach((field) => {
      this.changeField[field] = this.onChange.bind(this, field.name); 
    });
  }

  onChange(fieldName, event) {
    this.props.onChange(fieldName, event.target.value);
  }

  render() {
    const fields = this.props.fields.map((field) => {
      return <input value={field.value} onChange={this.changeField[field.name]}/>
    });

    return (
      <div>
        {fields}
      </div>
    );
  }
}

I created a simple utility memobind to address this problem, any comment is welcome. https://github.com/supnate/memobind

Okey I understand. And what about es7 class properties ?

mapRef = (c) => {
  this._input = c;
};

It'll bind this without the constructor.

More Issues: