Categories
JavaScript React

How to Add a React Input with a Required Attribute?

Spread the love

In a React app, if we want to add input with a required attribute, then we can’t just use the required attribute since we’re supposed to handle all the form input changes ourselves.

However, we can make this task easier by using a library to make our lives easier.

The React Hook Form package lets us add an input field with a required attribute and enforce it by providing functions that we can pass into the props of an input element to enforce an input value to be entered.

To start, we run:

npm install react-hook-form

Then we can write the following to add an input box that requires an input value before form submission.

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => console.log(data);
  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmit)}>
        <input name="requiredField" ref={register({ required: true })} />
        <br />
        {errors.requiredField && <span>This field is required</span>}
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

We have an input element that has the ref prop set to the object returned by the register function that’s returned by the useForm hook.

{ required: true } is passed into the register function to make this input a required input.

We also set the name attribute with a name so that we can display form validation error messages below it, which is stored in the returned errors object.

The errors object is returned by useForm and has the form validation errors with the name attribute values of each input element as the keys and true if there are errors in the input field value and false otherwise.

handleSubmit is the form submit event handler, and it doesn’t run until all form input values in the form are valid.

We just log the entered values, which are stored in the data parameter as an object with the keys being the name attribute values of each input and the values being the corresponding input values for each input.

Form validation errors are only detected after we type in something for the first time.

With the React Hook Form package, we can add a React input that acts like it has the required attribute set to true.

We can set an input to be a required input element by passing in some props.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *