CodexBloom - Programming Q&A Platform

React Final Form not updating state for dynamically added fields

👀 Views: 67 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-06
react final-form dynamic-forms javascript

I've tried everything I can think of but I'm reviewing some code and I'm having trouble with I'm confused about I'm trying to debug Hey everyone, I'm running into an issue that's driving me crazy. I'm using React Final Form to manage my form's state, and I'm facing an issue where dynamically added fields are not reflecting their values in the form state. I have a button that allows users to add new input fields, but once added, these fields do not seem to be tracked properly by the form. Here's a simplified version of my code: ```javascript import React from 'react'; import { Form, Field } from 'react-final-form'; const DynamicForm = () => { const [fields, setFields] = React.useState([0]); const addField = () => { setFields([...fields, fields.length]); }; return ( <Form onSubmit={values => console.log(values)} render={({ handleSubmit }) => ( <form onSubmit={handleSubmit}> {fields.map((field, index) => ( <Field name={`field${index}`} key={index}> {({ input }) => <input {...input} placeholder={`Field ${index + 1}`} />} </Field> ))} <button type="button" onClick={addField}>Add Field</button> <button type="submit">Submit</button> </form> )} /> ); }; ``` When I add a new field and type something into it, the new field's value does not appear in the `values` object when I submit the form. I have checked that the `Field` names are unique and the `key` prop is set correctly, but it still doesn't work as expected. I've also tried using `FormSpy` to monitor the form state, and it confirms that only the initial fields are being tracked. The version of React Final Form I'm using is 6.5.6. Is there something I'm missing regarding state management with dynamically added fields or any best practices I should follow to ensure the values are captured correctly? Thanks in advance! Any pointers in the right direction? This is my first time working with Javascript stable. I'm on CentOS using the latest version of Javascript. What's the best practice here? What's the best practice here? What would be the recommended way to handle this?