Published: April 29 2021

React Hook Form 7 - Required Checkbox Example

Example built with React 17.0.2 and React Hook Form 7.3.5

Other versions available:

This is a quick example of how to implement a required checkbox field in React with the recently released version 7 the React Hook Form library. For a more detailed registration form example that includes a bunch of other fields see React Hook Form 7 - Form Validation Example.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/react-hook-form-7-required-checkbox-example)


React Hook Form 7 Required Checkbox App Component

The app component contains an example form built with the React Hook Form library that contains a single required checkbox.

Form validation rules are defined with the Yup schema validation library and passed with the formOptions to the React Hook Form useForm() function, for more info on Yup see https://github.com/jquense/yup.

The checkbox is set to required with the rule Yup.bool().oneOf([true], 'Accept Ts & Cs is required').

The useForm() hook function returns an object with methods for working with a form including registering inputs, handling form submit, resetting the form, accessing form state, displaying errors and more, for a complete list see https://react-hook-form.com/api/useform.

The onSubmit() method is called when the form is valid and submitted, and simply displays the form data in a javascript alert.

The returned JSX template contains the form with the required checkbox field and validation message. The form field is registered with the React Hook Form by calling the register function with the field name from the input element (i.e. {...register('acceptTerms')}).

import React from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

function App() {
    // form validation rules 
    const validationSchema = Yup.object().shape({
        acceptTerms: Yup.bool()
            .oneOf([true], 'Accept Ts & Cs is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, reset, formState } = useForm(formOptions);
    const { errors } = formState;

    function onSubmit(data) {
        // display form data on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(data, null, 4));
        return false;
    }

    return (
        <div className="card m-3">
            <h5 className="card-header">React Hook Form 7 - Required Checkbox Example</h5>
            <div className="card-body">
                <form onSubmit={handleSubmit(onSubmit)}>
                    <div className="form-group form-check">
                        <input name="acceptTerms" type="checkbox" {...register('acceptTerms')} id="acceptTerms" className={`form-check-input ${errors.acceptTerms ? 'is-invalid' : ''}`} />
                        <label htmlFor="acceptTerms" className="form-check-label">Accept Terms & Conditions</label>
                        <div className="invalid-feedback">{errors.acceptTerms?.message}</div>
                    </div>
                    <div className="form-group">
                        <button type="submit" className="btn btn-primary mr-1">Register</button>
                        <button type="button" onClick={() => reset()} className="btn btn-secondary">Reset</button>
                    </div>
                </form>
            </div>
        </div>
    )
}

export { App };

 


Need Some React Hook Form Help?

Search fiverr for freelance React Hook Form developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by