CodexBloom - Programming Q&A Platform

ReactJS - Handling form state with dynamic fields and validation without using Formik

👀 Views: 30 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
reactjs hooks form-validation JavaScript

Could someone explain I'm relatively new to this, so bear with me... I just started working with I'm having a hard time understanding I've looked through the documentation and I'm still confused about I'm currently developing a dynamic form in React where users can add or remove fields on the fly. Specifically, I want to manage the state of these fields without using a library like Formik. The issue arises when trying to validate these dynamically added fields. I'm using React 18 and functional components with hooks. Here's a simplified version of my code: ```jsx import React, { useState } from 'react'; const DynamicForm = () => { const [fields, setFields] = useState([{ id: Date.now(), value: '' }]); const [errors, setErrors] = useState({}); const handleChange = (id, value) => { setFields(fields.map(field => field.id === id ? { ...field, value } : field)); }; const handleAddField = () => { setFields([...fields, { id: Date.now(), value: '' }]); }; const handleRemoveField = (id) => { setFields(fields.filter(field => field.id !== id)); }; const validateFields = () => { const newErrors = {}; fields.forEach(field => { if (!field.value) { newErrors[field.id] = 'This field is required'; } }); setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e) => { e.preventDefault(); if (validateFields()) { console.log('Form submitted:', fields); } }; return ( <form onSubmit={handleSubmit}> {fields.map(field => ( <div key={field.id}> <input type='text' value={field.value} onChange={(e) => handleChange(field.id, e.target.value)} /> {errors[field.id] && <span style={{ color: 'red' }}>{errors[field.id]}</span>} <button type='button' onClick={() => handleRemoveField(field.id)}>Remove</button> </div> ))} <button type='button' onClick={handleAddField}>Add Field</button> <button type='submit'>Submit</button> </form> ); }; export default DynamicForm; ``` When I submit the form, I see validation errors appearing correctly. However, if I remove a field that had an error before, the error message for that field persists even after it's removed from the state, which causes confusion for users. I'm currently setting the errors state directly based on the current fields, but it seems like it doesn't properly clear out removed fields from the error messages. I've tried adding a cleanup step after removing a field, but it seems cumbersome and not intuitive. How can I ensure that the errors state reflects the current state of the fields dynamically and doesn't retain messages for removed fields? Also, any general tips on optimizing performance with dynamic forms in React would be greatly appreciated. I'm working on a web app that needs to handle this. For reference, this is a production application. Thanks for taking the time to read this! Am I approaching this the right way? The stack includes Javascript and several other technologies. Thanks in advance! The project is a service built with Javascript. Any ideas what could be causing this? I'm on CentOS using the latest version of Javascript. Is this even possible?