Blog>
Snippets

Implementing Conditional Form Logic

Exhibit how to implement conditional logic within a form managed by useForm, such as showing or hiding fields based on other field values, to handle complex form scenarios.
import React from 'react';
import { useForm } from 'react-hook-form';
Import necessary functionality from react and react-hook-form.
const FormComponent = () => {
  const { register, watch, handleSubmit } = useForm();
  const watchShowAge = watch('showAge', false); // You can watch specific field
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>Show Age</label>
      <input type='checkbox' {...register('showAge')} />

      {watchShowAge && (
        <div>
          <label>Age</label>
          <input type='number' {...register('age')} />
        </div>
      )}

      <input type='submit' />
    </form>
  );
};
This code example shows how to implement conditional logic within a form using useForm from React Hook Form. It watches the 'showAge' field for changes. If 'showAge' is checked, the 'Age' input field is displayed. This demonstrates hiding or showing form fields based on the value of another field.
export default FormComponent;
Exports the FormComponent so it can be used in other parts of the application.