0

I want to build a complex form in react. It is a matrix of input and I need to do operations when the value of an input change. I would like to call the same function for the "onchange" of all the inputs, but I need to know which input has called the function. What is the best way to do that ?

Is it a good idea to store all my input values in a javascript array that I store in the state of my component. I could manipulate this array in my function when the value on an input change. I'm not sure it's a good practice.

Any suggestions ? I'm new to React and all the examples I find are with simple forms. Thanks !

Mathieu
  • 157
  • 3
  • 9

1 Answers1

0

You could do something like this:

class MyComponent extends React.Component
  _createOnChangeFunction = (inputIndex) => {
    return () => {
      // The magic of closures helps you out here
      console.log(`INPUT ${inputIndex} CHANGED`);
    }
  }

  render() {
    myElements = [];
    for(i = 0; i < NUMBER_OF_INPUTS; i++) {
      myElements.push(<input type='checkbox' value={i} onChange={this._createOnChangeFunction(i)} />);
    }

    return (
      <div>
        {myElements}
      </div>
    }
  }

}

(Note that you'd have to provide the NUMBER_OF_INPUTS and what you actually want to do in the function)

For a good example of the closure thing I used, check out this post: How do JavaScript closures work?

Community
  • 1
  • 1
Ben Hare
  • 4,365
  • 5
  • 27
  • 44