1

I am mapping a list of data, within this list is some input fields. Usually I would use the useState hook to manage the data for the input field, but in this situation the number of input will be determined by data coming from an api, meaning there could be two input fields or ten.

My question is how can I dynamically handle the state per input field?

Here's an example:

{
  data.map((item, i) => {
    <div key={i}>
      // There could be 2 inputs or 10 input fiels
      <span>Input Number</span>
      <input value="" onChange={() => updateStatefunction()} />
    </div>;
  });
}
herbie
  • 335
  • 2
  • 14
  • I'm sure there's a duplicate for this somewhere so I'll write this in a comment, but creating a single state variable containing an array, and storing each input's value at a set index is a common approach. – DBS Jan 26 '23 at 11:23
  • Thanks @DBS, so it would be something like const [state, setState] = useState([index: "", value: ""]) ? – herbie Jan 26 '23 at 11:26
  • Here we go, this seems like the duplicate I was looking for: [How to implement a dynamic form with controlled components in ReactJS?](https://stackoverflow.com/questions/42316604/how-to-implement-a-dynamic-form-with-controlled-components-in-reactjs) (The top answer is using class based React, but there's a few functional approaches below it) – DBS Jan 26 '23 at 11:28
  • I'm afraid the site doesn't let me mark a question as a duplicate twice, but it's not a big problem, it will get tidied up eventually. Or if your problem is solved entirely by that duplicate, you could just delete the question. – DBS Jan 26 '23 at 11:37
  • Actually I'm still confused, In the example you have posted, the number of inputs is preposed from the state, in my case it won't be, its 100% dynamic. – herbie Jan 26 '23 at 12:06

0 Answers0