23

React Hook Form — An Elegant Solution to Forms in React

 4 years ago
source link: https://blog.bitsrc.io/react-hook-form-an-elegant-solution-to-forms-in-react-4db64505b0cd
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

React Hook Form — An Elegant Solution to Forms in React

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

RjeMry7.jpg!web

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.

If you’re using a cloud component hub like Bit.dev , to publish and organize your reusable UI components, you’ll find React Hook Form very easy to work with. It’s simpler to integrate your reusable React components with a hooks-based and lightweight library than it is with other large and highly opinionated from libraries.

uyM3Ejm.jpg Published React components on bit.dev — easy to integrate with react-hook-form

To make things as clear as possible, let’s start with a 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:

  • Line 4 & 24: create a state and attach the value.
  • line 10 & 24: create a handle change function and add onChange event of every field.
  • line: 6 & 7: And the handleSubmit and all the handleChange function has to call the bind function.
  • 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.

If you have not yet come across React hooks I recommend you to go through the following post.

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 :innocent:. 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:
------- CASE 1 -------When name attribute is:
name="phoneNumber"Form submitted data is:
{ phoneNumber: "9911" }------- CASE 2 -------When name attribute is:
name="form1.phoneNumber"Form submitted data is:
{ form1: { phoneNumber: "9911" } }------- CASE 3 -------When name attribute is:
name="form1.phoneNumber[0]"  // 0 is the index. It can be any intForm submitted data is:
{ form1: { phoneNumber: ["9911"] } }

2) Adding validation

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

errors

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 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.

phoneNumber

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 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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK