As developers, one of the essential aspects of working with forms is controlling user inputs efficiently. Using the useForm hook from react-hook-form, we can easily manage forms with simplicity and flexibility.
Hereโs a quick example showing how to dynamically update a form input using the setValue function:
import { useForm } from 'react-hook-form';
function MyForm() {
const { register, setValue } = useForm();
const updateValue = () => {
setValue('username', 'newUserName'); // Dynamically update username
};
return (
<form>
<input {...register('username')} placeholder="Enter Username" />
<button type="button" onClick={updateValue}>Set Username</button>
</form>
);
}
In this code, clicking the button updates the username field dynamically! ๐ A simple yet powerful way to control form values in React.
Check out the image below for a visualization of the developerโs workspace:
Top comments (0)