React Hook Form — An Elegant Solution to Forms in React

栏目: IT技术 · 发布时间: 4年前

内容简介: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 likeTo make things as clear as possible, let’s start wi

React Hook Form — An Elegant Solution to Forms in React

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

React Hook Form — An Elegant Solution to Forms in React

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.

React Hook Form — An Elegant Solution to Forms in React
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

以上所述就是小编给大家介绍的《React Hook Form — An Elegant Solution to Forms in React》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Algorithms, 3rd Edition

Introduction to Algorithms, 3rd Edition

Thomas H. Cormen、Charles E. Leiserson、Ronald L. Rivest、Clifford Stein / The MIT Press / 2009-7-31 / USD 94.00

Some books on algorithms are rigorous but incomplete; others cover masses of material but lack rigor. Introduction to Algorithms uniquely combines rigor and comprehensiveness. The book covers a broad ......一起来看看 《Introduction to Algorithms, 3rd Edition》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具