React Hook Form Basic (React Native)

Share this post on:

Why to use React Hook Form? 

React Hook form manages complex form states and provides better performance than other libraries like formik. It provides the facility to validate the form on onChange and onSubmit. Also, it is lightweight and has no dependencies. 

Installation  

To install the react-hook-form library, execute the following command from the terminal: 

command: npm install react-hook-form

React Hook Form Validation 

It provides multiple validations on each field. It supports a list of validation rules. 

  • required: input value is mandatory or not. 
  • pattern: a regex pattern to validate the input value. 
  • min: minimum value to be acceptable. 
  • max – maximum value to be acceptable. 
  • minLength: minimum length of input that can be acceptable. 
  • maxLength: maximum length of input that can be acceptable. 
  • validate: Any custom function to validate the input value.

When validations are applied to each field? 

It’s based on the mode set while creating the form state, the default mode set is “onSubmit” and it supports a list of validation rules. 

  • onBlur 
  • onChange 
  • onSubmit 
  • onTouched 
  • all 

How to create a form? Example of Login:

  •  Let’s create email input 

In the above input,

  • label is the text that we want to display upon the input 
  • name is the key that is equivalent to  defaultvalue for our email field 
  • control object is created by useForm() and it is must required to get the current state of the field 
  • isMandatory field is the validation which mentions required key which will be boolean value that field is required or not. 
  • IsEmail field is the validation which mentions pattern key which will be boolean value that field should be in email pattern or not. 

So, from above example isMandatory is related to required field rule and IsEmail is related to pattern rule. And as given below we can get values of fields by handle submit function.

Mounting 

Component mounting is faster with react hook form compared to others. The following screenshots demonstrate the same. 

Share this post on: