Site icon RemoteStack

How to Set Required Checkbox with React Hook Form 7

In this comprehensive tutorial, we will learn how to create a checkbox form element in React application. We will check out how to make the required checkbox field in React using the React Form Hook 7 and Yup packages.

We will build a simple React hook form checkbox component, and you will be making it a required checkbox.

To validate the checkbox in React, a user has to click on the submit button, and an error message will appear only when the checkbox field is unselected.

If the checkbox is selected, we will show the checkbox values in the browser console.

We will use the Yup schema validation package that works magically with React hook form’s useForm() method.

This way, we will handle form creation and validation simultaneously without spending much time, and we are sure it will make your day a heyday.

React Hook Form Build Checkbox Component Example

Getting Started<

You have probably created an app, however if you haven’t then go to command line tool and execute the provided command.

npx create-react-app react-form-app

Also, jump into the new project folder with this command.

cd react-form-app

Install Required Packages

Now, this step will reveal how to easily install both the required packages in React app.

You have to execute the following command from the command prompt to add React Hook Form and Yup plugins.

npm install @hookform/resolvers
npm install yup

Install Bootstrap

We have a task to create a form with a checkbox that has to show error messages. On this voyage, we have to deal with CSS, and writing CSS takes time.

So, here is the idea, add the bootstrap in React and save your time.

npm install bootstrap

Create Required Checkbox

In this step, we will show you the best way to make the checkbox field a required element is.

Off-course, we will take the help of the Yup and React hook form to create and validate the checkbox field.

Hence, make the new file in component/ folder and ensure that you name it HookCheckbox.js.

Append entire code in HookCheckbox.js file.

import React from 'react'

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

export default function HookCheckbox() {
  const yupValidation = Yup.object().shape({
    selectTc: Yup.bool().oneOf([true], 'Please Select Term and Conditions'),
  })

  const setFormOptions = { resolver: yupResolver(yupValidation) }

  const { register, handleSubmit, reset, formState } = useForm(setFormOptions)
  const { errors } = formState

  function onSubmit(data) {
    console.log(JSON.stringify(data, null, 4))
    return false
  }

  return (
    <div>
      <h2>React Required Checkbox Example</h2>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="form-group">
          <div className="form-check">
            <input
              type="checkbox"
              name="selectTc"
              {...register('selectTc')}
              id="selectTc"
              className={`form-check-input ${
                errors.selectTc ? 'is-invalid' : ''
              }`}
            />

            <label htmlFor="selectTc" className="form-check-label">
              Check me out
            </label>

            <div className="invalid-feedback">{errors.selectTc?.message}</div>
          </div>
        </div>
        <div className="d-grid mt-2">
          <button type="submit" className="btn btn-danger">
            Submit
          </button>
        </div>
      </form>
    </div>
  )
}

Update App Js

The app js is the main component of React, all the new components you create should go into src/App.js file.

By following this procedure, you register the component in the app and make the new module available throughout the app.

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css';
import HookCheckbox from './components/HookCheckbox'


export default function App() {
  return (
    <div className="container mt-2">
      <HookCheckbox />
    </div>
  )
}

Start App Server

Up until now all the formalities have been done, time has eventually come to evoke the application server.

It could be done with the given command, head over to terminal type the command and hit enter to manifest the app on the browser.

npm start

Summary

In this simple guide, we described how to add a required checkbox form field in React application in simple steps.

We used the two profound and popular packages to set the required checkbox field, React Hook Form and Yup form schema.

You can also create the more advanced form using both the packages; the soulful assembly of hook form and Yup helps you develop and validate forms faster.

Exit mobile version