DEV Community

Milad Joodi
Milad Joodi

Posted on

πŸš€ Mastering Form Handling in React: Using setValue with useForm! πŸ’»

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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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:

React #WebDevelopment #JavaScript #Forms #useForm #reactHookForm #CodingTips #DynamicForms

Top comments (0)