Home > Mobile >  How to manage dynamic form data using useState?
How to manage dynamic form data using useState?

Time:12-09

I have a form that gets it's input fields dynamically, it can have hundreds of fields so i can't create a state individually, I was planning on doing something like using an object using the unique key of a form field but need some help.

Suppose the form has fields like this.

<form>
 {inputFields.map((i) => {
    <input type={i.type} />
  })}
</form>

Now i would need a state like the one below

 inputState = {
  "INPUT_FIELD_NAME1": "INPUT FIELD VALUE 1",
  "INPUT_FIELD_NAME2": "INPUT FIELD VALUE 2",
  "INPUT_FIELD_NAME3": "INPUT FIELD VALUE 3",
}

I need help with this, how do i set values in such a manner in my input onChange and how do i access the values from the state and use them for the matching input field?

CodePudding user response:

I would do something like this:

const [form, setForm] = useState({})

const onChange = (event) => {
   const { id, value } = event.target
   setForm((prev) => ({ ...prev, [id]: value }))
}

<form>
   {inputFields.map((i) => {
      <input key={i.id} onChange={onChange} id={i.id} type={i.type} />
   })}
</form>

Id must be unique, also you can use "name" property instead of "id"

CodePudding user response:

As per my understanding and knowledge, you have to update your dynamic structure like given as below

 <form>
    {inputFields.map((i) => (
      <input
        type={i.type}
        name={`INPUT_FIELD_NAME${i.id}`}
        onChange={handleChange}
      />
    ))}
  </form>

Also have to update your react state on input change like

const [inputState, setinputState] = useState({});
const handleChange = (e) => {
  const { name, value } = e.target;
  setinputState({
    ...inputState,
    [name]: value
  });
};

I hope it will work for you! Thanks.

  • Related