Summary of use of react hook form

Form state management has always been a headache for the front-end. Error prompts, verification rules, dynamic forms, reset... Make a big head. Fortunately, many good community programs have emerged in recent years, such as Formik, react-hook-form, react-final-form Wait, today we'll talk about the react hook form.

useForm

useForm is the most basic form status management hook. It accepts the following parameters:

const {
  handleSubmit,
  watch
} = useForm({
  defaultValues: {},
  mode: 'onSubmit' // onChange | onBlur | onSubmit | onTouched | all
})

mode can control the timing of triggering verification. If we want users to feel that there is an error in filling in as soon as possible, we can use 'all';

defaultValues: if the form is pulled down from the background and the data has initial values, it can be passed in from here.

rules

rules can be used to verify values and support the following fields:

{
required: true,
maxLength; // Maximum length
minLength; //Minimum length
max: 5 // Maximum
min: 5 // minimum value
pattern: /1\d{12}/
validate: (v) => v > 100
validate: {
	greaterThan: (v) => v > 100,
	lessThan: (v) => v< 200
	}
}

Use < controller / > to integrate with UI Library

Using the register function returned by useForm, we can easily use the native html elements to build a form, but in most cases, we use the UI library to develop the form.

< controller / > the component accepts the control, name, rules and render functions as attributes. The render function accepts three parameters: field, fieldState and formstate: the field contains the onChange function and value used to control the field, and the fieldState contains the verification information of the field. Through this information, we can control how this field should be rendered;

    field: { onChange, onBlur, value, name, ref },
    fieldState: { invalid, isTouched, isDirty, error },
    formState,
<Controller
  control={control}
  rules={{ required: true }}
  name="test"
  render={({
    field: { onChange, onBlur, value, name, ref },
    fieldState: { invalid, isTouched, isDirty, error },
    formState,
  }) => (
    <Checkbox
      onBlur={onBlur} // notify when input is touched
      onChange={onChange} // send value to hook form
      checked={value}
      inputRef={ref}
    />
  )}
/>

watch and useWatch build dynamic forms

There are often such scenes, that is, an input will affect the next form display. Because the form state of useForm changes, it does not necessarily trigger re rendering. When we need to update the UI when the value changes, we need to use useWatch or watch;

Suppose there is a scenario where we need to echo the user's input in real time, it can be written as follows:

const watchedName = watch('name', '');

return <div>
    <label>Name</label>
    <input
        type="text"
            {...register("name", { required: true, maxLength: 50 })}
    />
    <div>name: {watchedName}</div>
</div>

At this time, when the field of the input box is updated, it will trigger re rendering, so as to echo the value entered by the user. So what is the difference between watch and useWatch? Watch is the return value of useForm hook. useWatch is a brand-new hook function, which can achieve better performance in some scenarios without parent component update. The following example passes the watch into the child component. It can be found that the parent component is also updated when the child component is updated.

useFieldArray to add a table item

We often encounter such a scenario - adding form items, such as adding a receiving address. The use hook form provides us with the useFieldArray hook to complete these tasks:

  const { register, control, handleSubmit, reset, watch } = useForm({
    defaultValues: {
      test: [{ firstName: "Bill", lastName: "Luo" }]
    }
  });
  const {
    fields,
    append,
    prepend,
    remove,
    swap,
    move,
    insert,
    replace
  } = useFieldArray({
    control,
    name: "test"
  });

We can use prepend to insert a form item at the head of the queue, append to insert a form item at the end of the queue, and remove to remove a form item. Of course, if we want to display the data in the form item in real time, we still need to use watch and useWatch

Added by d3chapma on Sat, 05 Feb 2022 19:55:10 +0200