How to Create a Required Checkbox Using Next.js and React Hook Form

How to create a required checkbox field in Next.js using the React Hook Form

Picture of Nsikak Imoh, author of Macsika Blog
Abstract background with the Text How to Create a Required Checkbox Using Next.js and React Hook Form
Abstract background with the Text How to Create a Required Checkbox Using Next.js and React Hook Form

Table of Content

This short Next.js code snippet shows you a working example of how to develop a required checkbox field in Next.js using the React Hook Form library.

We will also be using the Yup library for validation, although you can use React Hook form’s validation without the need for Yup.

Read More: How to Resolve the Module not found: Can’t resolve ‘fs’ error in Next.js and WebPack

Example of Required Checkbox Using Next.js and React Hook Form

The example we will build is a simple user form with a required checkbox property to accept terms and conditions.

Here is a code example of creating a required checkbox using next.js and react hook form.

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({
        acceptTermsandConditions: Yup.bool()
            .oneOf([true], 'You must accept terms & conditions.')
    });
    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="acceptTermsandConditions" type="checkbox" {...register('acceptTermsandConditions')} id="acceptTermsandConditions" className={`form-check-input ${errors.acceptTermsandConditions ? 'is-invalid' : ''}`} />
                        <label htmlFor="acceptTermsandConditions" className="form-check-label">Accept Terms & Conditions</label>
                        <div className="invalid-feedback">{errors.acceptTermsandConditions?.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>
    );
}
Highlighted code sample.

Explanation of Code Example

We created a Home component that contains a form consisting of a single required checkbox, built with the React Hook Form library.

The JSX template we return from the Home component contains the form with the required checkbox field and validation message.

Using the Yup schema validation library, we define the form validation rules.

We pass these rules with the formOptions to the React Hook Form useForm() hook function.

The checkbox is set to required with the validation rule from using Yup as Yup.bool().oneOf([true], 'You must accept terms & conditions.').

The useForm() hook function from React Hook form returns an object with methods for working with a form such as registering form inputs, handling form submission, resetting the form, accessing form state, displaying errors, and more.

We register the form field with React Hook Form library by calling the register function with the field name from the input element (i.e. {...register('acceptTermsandConditions')}).

We call onSubmit() method from React Hook form when the form passes all validations and gets submitted.

This point is where you send an update or post data to the API endpoint that does something with the form data.

In this example, when the form successfully passes all validations and gets submitted, we simply display the form data in a JavaScript alert.

Read More: What is Next.js On-demand Incremental Static Regeneration and How to Use it?

Wrap Off

In this short tutorial, we looked at how to create a required checkbox field in Next.js using the React Hook Form library.

Our example is a simple form that requires you to accept the terms and conditions before submission can occur.

Validations were done using the Yup library.

If you learned in this tutorial, please consider sharing and subscribing to our newsletter.

If you have any questions, please feel free to contact us

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?