Published:

Next.js - Required Checkbox Example with React Hook Form

Example built with Next.js 11.1.0 React Hook Form 7.12.1

Other versions available:

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

Here it is in action: (See on CodeSandbox at https://codesandbox.io/s/next-js-required-checkbox-example-1yog0)


Next.js Home Page with Required Checkbox

The home page 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 { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

export default Home;

function Home() {
    // 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">Next.js - 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>
    );
}

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some NextJS Help?

Search fiverr to find help quickly from experienced NextJS developers.



Supported by