Home > database >  Trying to dynamically create number of fields in a form - A component is changing a controlled input
Trying to dynamically create number of fields in a form - A component is changing a controlled input

Time:07-25

So, because I have multiple forms on multiple pages, I thought it'd be better to have some components which dynamically create the number of rows needed in a form.

I have just tried this approach: https://stackblitz.com/edit/react-ts-eynfaa

but I get

A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen.

and if I console.log the formValues on submit I don't get the desired output.

So, is there something wrong with my approach? How can I fix it?

Thanks.

CodePudding user response:

Your call to setFormValues in updateValue function of CreateRow component is overriding formValues state object (note that setState from hooks and set state of React class components work differently - see docs), effectively removing all values apart from the one currently set. You can simply fix this by spreading the current formValues object like so:

setFormValues({ ...formValues, [e.target.name]: e.target.value });
  • Related