Dynamic Form Handling using react-hook-form

Happy New Year to Everyone ❤️

Please check my previous blog Simple Form Handling if you are new here.

In this blog I will explain how can we use watch in react-hook-form to dynamically add and remove elements on the form.

It's a very simple Form say user has to select the programming languages known, based on it a new checkbox elements will be added on UI and user has to select different frameworks known in the selected language.

When no programming language is selected.

Selection_045.png

When any one programming language is selected.

Selection_044.png

So there are 2 questions right now,

  1. How do we know when the checkbox is selected?
  2. How to handle values of the new element added?
  • How do we know when the checkbox is selected?

react-hook-form provides us a way to observe all the form fields that are registered using watch function provided. To watch all the fields, use watch() without any arguments.

    const { register, handleSubmit, watch } = useForm()

    const watchFields = watch()

To watch some of the fields, use watch(array of string) with array of registered names.

    const { register, handleSubmit, watch } = useForm()

     const watchFields = watch(['languagesKnown'])

This will watch only one field registered as languagesKnown

There are some rules that you should check out as they are important.

if we watch all fields using watch(), watchFields variable return the list of values that are observed.

Selection_047.png

Based on the watchFields variable we add or remove elements to the UI.

watchFields.languagesKnown?.map((lang) => {
  return (
    <Grid item xs={6} key={lang}>
      <FormControl component="fieldset">
        <FormLabel component="legend">{`Please select known frameworks in ${lang}`}</FormLabel>
        {frameworks[lang].map((fm) => {
          return (
            <FormControlLabel
              key={fm}
              control={<Checkbox value={fm} {...register(lang)} />}
              label={fm}
            />
          );
        })}
      </FormControl>
    </Grid>
  );
});

During the first render watchFields can return null or undefined so its good to use optional chaining.

  • How to handle values of the new element added?

Values are handled automatically be react-hook-form all you need to do is register the fields with the name.

When form is submitted.

That's all for dynamic form handling.

Full Code can be found at github.