gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
hello! how to update form values with provided object in React Hook Form?
- User
hello! how to update form values with provided object in React Hook Form?
- Assistant
You can use the
resetmethod provided by React Hook Form to update the form values with a provided object.Here's an example:
import React from 'react'; import { useForm } from 'react-hook-form'; const MyForm = () => { const { register, handleSubmit, reset } = useForm(); const onSubmit = (data) => { console.log(data); }; const updateFormValues = () => { const newData = { firstName: 'John', lastName: 'Doe', email: 'john.doe@example.com', }; reset(newData); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input type="text" name="firstName" ref={register} /> <input type="text" name="lastName" ref={register} /> <input type="email" name="email" ref={register} /> <button type="submit">Submit</button> <button type="button" onClick={updateFormValues}>Update Form Values</button> </form> ); }; export default MyForm;In the example above, the
updateFormValuesfunction is called when the "Update Form Values" button is clicked. It creates a new object with updated values, and passes it to theresetmethod to update the form values.