01 logo

React Hook Form - An Elegant Solution to Forms in React

How to use react-hook-form to build clear and maintainable React forms.

By Mahesh HaldarPublished 3 years ago 4 min read
Like

React Hook Form represents to me the middle ground between implementations using heavy form libraries, on one side, and cumbersome plain React forms, on the other.

Let's start with simple vanilla React form with only a single 'phone number' field to handle.

Please follow the above piece of code for one field basic form to capture the phone number from the user. For every input field in a form we have to do the following:

  1. Line 4 & 24: create a state and attach the value.
  2. line 10 & 24: create a handle change function and add onChange event of every field.
  3. line: 6 & 7: And the handleSubmit and all the handleChange function has to call the bind function.
  4. On every keystroke, we have to handle change and update the state so that the same is reflected in UI.

The complexity grows when we have a myriad of fields, validation rules, and conditional input fields.

In this post, let’s explore an elegant way of creating react forms that are built on the basis of React Hooks. The react hooks have made the whole react more exciting, maintainable and react dev have to write lesser code.

React hooks are an amazing addition to the latest react, which enables the functional components to use features like state, context, lifecycle methods, ref, etc. Hooks reduces the amount of code to achieve the same functionality and makes the code more readable and maintainable.

Please follow this link to know, why react-hook-form is performant and want to see a detailed comparison among formik, redux form, and react-hook-form.

Let’s list down a few of the use cases of forms where we will see the react hook form in action and understand how can we use react-hook-form to make our life easy by creating elegant forms that are easy to maintain and are more performant.

1) Basic form with submit

Let's use react-form-hook to convert the same phone number capture form that we wrote using vanilla react.

Please notice we have reduced from 30 lines to 19 lines 😇. That's quite clean with lesser code, configs, and lesser functions.

Let's try to understand the important parts of the react-hook-form.

  • Line 2: import the useForm hook from the library
  • Line 4: write the function to handle submit. Note the form data would be captured in the function parameter.
  • Line 9: get register and handleSubmit from the hook.
  • Line 11: attach the hook’s handleSubmit to form and our submit handler.
  • Line 14: register the input or select field into the React Hook form. Please note we are using the HTML name attribute to give a unique name to the field.

This name becomes the key to the value of the submitted data.

The following are some use cases, we should be aware of when adding name attribute to our form fields:

2) Adding validation

Let's enhance our phone number capture form by adding some validation. Validations in the react form hook have replicated the HTML validation rules like required, min, max, minLength, maxLength, pattern, etc. Attach these rules in ref with the register function.

  • line 10: get the errors to object from useForm hook. The empty object signifies no error.
  • line 20: attach the validation on each field.

3) Adding error messages

In the previous section, we added some validation rules. Let's enhance our form by adding some customized messages.

  • Lines 21 & 25: we can add a custom error message to each validation type and input field. And whenever the validation rule is violated the respective message is added in the error object.

4) Listening to the input field change

Many times we need to subscribe to input and reflect the changes in some other component. which is located outside the form.

We can use watch from the react-form-hook.

  • Line 10: get the watch function from the hook.
  • Line 17: call the watch function and subscribe to any field from the form.
  • Result: as we modify the phoneNumber, the latest value is reflected.

5) Creating conditional input fields

Many times we require to create dynamic and conditionally render input fields on UI. Let's assume we need to fulfill the following requirement:

  • Given I am a customer and I have navigated to provide the phone number and dob screen
  • When I click on the show date picker checkbox
  • Then I see a new input field in the form
  • So that I can select the date of birth and submit the form
  • And when I unselect the checkbox
  • Then the date picker disappears

Let's try to achieve the above conditional form

  • Line 40: set up a checkbox.
  • Line 12: using the watch, get the current value if the checkbox is checked or not.
  • Line 43: use react's conditional rendering and if checked then render the date picker

React-hook-form is an elegant solution to easily create and maintain forms in React. The beauty is that, after using a form-hook, still the form creation is done in a classic way of creating forms, viz. no new HOC component or no wrappers.

Please share your view on this.

That's all for this post I hope this was helpful.

Keep on learning, keep on Reacting and forming :)

how to
Like

About the Creator

Mahesh Haldar

Full stack Developer.

Hindi Story teller at https://www.youtube.com/c/eklifafa

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.