Actualmente, tengo este estado con formData.
Al escribir algún texto, en lugar de cambiar el nombre completo.primer nombre. está creando otra propiedad y simplemente configurando un valor único (como en una sola letra).
const [formData, setFormData] = useState({ fullName: { firstName: "", lastName: "", }, email: "", password: "", confirmPassword: "", });Así es como configuro formData.
const handleChange = (event) => { const { value, name } = event.target; console.log(name, value); setFormData((prevFormData) => ({ ...prevFormData, [name]: value, })); };Este es mi JSX, puede verificar el atributo "nombre" en la entrada para obtener alguna referencia.
<div className="App"> <form onSubmit={onSubmit}> <h1>Submit Form Nested Object UseState</h1> <input text="text" placeholder="First Name" name="firstName" value={formData.fullName.firstName} onChange={handleChange} /> <input text="text" placeholder="Last Name" name="lastName" value={formData.fullName.lastName} onChange={handleChange} /> <input text="email" placeholder="email" name="email" value={formData.email} onChange={handleChange} /> <input text="password" placeholder="password" name="password" value={formData.password} onChange={handleChange} /> <input text="password" placeholder="confirm Password" name="confirmPassword" value={formData.confirmPassword} onChange={handleChange} /> <button>Submit</button> </form> {JSON.stringify(formData, null, 2)} </div>Cambie los nombres de los formularios así:
<form onSubmit={onSubmit}> <h1>Submit Form Nested Object UseState</h1> <input placeholder="First Name" name="fullName.firstName" value={formData.fullName.firstName} onChange={handleChange} /> <input placeholder="Last Name" name="fullName.lastName" value={formData.fullName.lastName} onChange={handleChange} /> <input placeholder="email" name="email" value={formData.email} onChange={handleChange} /> <input placeholder="password" name="password" value={formData.password} onChange={handleChange} /> <input placeholder="confirm Password" name="confirmPassword" value={formData.confirmPassword} onChange={handleChange} /> <button>Submit</button> </form>luego cambie su función handleChange a esto:
const handleChange = (event) => { const { value } = event.target; const [key,subkey] = event.target.name.split('.'); setFormData((prevFormData) => ({ ...prevFormData, [key]: subkey ? { ...prevFormData[key], [subkey]: value, } : value })); };