Blog>
Snippets

Basic useForm Setup

Demonstrate initializing useForm and attaching it to a simple form, showcasing how to manage state for a text input.
import { useForm } from 'react-hook-form';
Importing useForm hook from react-hook-form.
function SimpleForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('example', { required: true })} />
      {errors.example && <span>This field is required</span>}
      <input type="submit" />
    </form>
  );
}
Defining a SimpleForm component. Here we initialize useForm, destructure its returned objects, define an onSubmit function which logs form data to the console, and return simple form JSX. The 'register' function is used to register an input field named 'example' with validation for being required.