Published: October 05 2020

React - Required Checkbox Example with React Hook Form

Example built with React 16.13.1 and React Hook Form 6.8.6

Other versions available:

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

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


React Hook Form 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 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, 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 using the ref={register} attribute which registers the checkbox with its name.

import React from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers';
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')
    });

    // functions to build form returned by useForm() hook
    const { register, handleSubmit, reset, errors } = useForm({
        resolver: yupResolver(validationSchema)
    });

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

    return (
        <div className="card m-3">
            <h5 className="card-header">React - Required Checkbox Example with React Hook Form</h5>
            <div className="card-body">
                <form onSubmit={handleSubmit(onSubmit)} onReset={reset}>
                    <div className="form-group form-check">
                        <input name="acceptTerms" type="checkbox" ref={register} id="acceptTerms" className={`form-check-input ${errors.acceptTerms ? 'is-invalid' : ''}`} />
                        <label for="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 className="btn btn-secondary" type="reset">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