Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the event argument when binding functions in React?

I have an input HTML tag, where the onChange is currently

onChange={() => { this.props.someFunc(this.props.someVal, e.target.checked) }

However, I want to follow the es-lint no-bind rule (I want to avoid inline functions), and I'm having issues hadling the arguments for this onChange function.

In my constructor I have:

constructor() {
  super();
  this.state = {
    // some state
  };
  this._onChangeHandler = this._onChangeHandler.bind(this);
}

_this.onChangeHandler = (event, val) => {
  this.props.someFunc(event.target.checked, val);
}

render() {
  <div>
    {
      this.props.inputs.map((x) => {
        const someValue = // ...a calculated value

        return (
          <label
            }>
            <input
              onChange={ this._onChangeHandler(someValue) } // need BOTH someValue and the event
              checked={ aBool }
              type="checkbox"
              value={ anotherValue }/>
            <span>{ textHere }</span>
          </label>
        );
      })
    }
  </div>
}

I've taken a look at this post, but no luck so far. What do I need to do to be able to pass both a value and the event to a bound function?

like image 582
TheRealFakeNews Avatar asked Feb 06 '23 02:02

TheRealFakeNews


1 Answers

What if you use currying?

// Helper method that returns a function
const generateHandler = (value, method) => e => method(e, value)

// Apply the helper method
<input onChange={generateHandler(someValue, this._onChangeHandler)} />
like image 174
Giorgio Polvara - Gpx Avatar answered Feb 07 '23 19:02

Giorgio Polvara - Gpx