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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

长尾理论2.0

长尾理论2.0

安德森 / 乔江涛、石晓燕 / 中信出版社 / 2009-5 / 42.00元

《长尾理论2.0》是克里斯·安德森对所有问题最明确的回答。在此书中,他详细阐释了长尾的精华所在,揭示了长尾现象是如何从工业资本主义原动力——规模经济与范围经济——的矛盾中产生出来的。长尾现象虽然是明显的互联网现象,但其商务逻辑本身,却是从工业经济中自然而然“长”出来的,网络只是把酝酿了几十年的供应链革命的诸多要素简单地结合在一起了。同时,长尾理论转化为行动,最有力、最可操作的就是营销长尾,通过口碑......一起来看看 《长尾理论2.0》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具