Why Not Other React Library Forms?
It’s really simple, there are multiple good reasons:
- Performance is important and package size matters. This is a tiny library without any dependencies.
- Reduces the code to handle forms, with less complexity due to the Hooks. You can find a complete code comparison here.
- Minimizes the number of re-renders and faster mount, striving to provide the best user experience. Twenty times less than other packages like Formik or Redux Form.
- Easy to adopt as form state is inherently local, it can be easily adopted without other dependencies.
The following code will demonstrate basic usage.
The main component used is the
useForm Hook with the returned functions and variables:
register: To connect a field to rules or validation functions.
handleSubmit: To check and validate all fields before sending submit.
watch: This will watch specified inputs and return their value.
errors: Contains form errors or error messages that belong to each input.
Each field needs a specific unique name that you will also use for labels and then you will pass the
register Hook to the
Inside it, you will pass multiple parameters. Required is needed to tell if the user has to enter that field and then you will be able to easily use other standard HTML rules.
Here’s the list of validation rules supported:
The validate function is a great way to use custom logic specific to that field, enabling you to implement custom behavior very easily.
validate: (value) => value === '1'
Handle Fields Errors
React Hook Form provides an
errors object to show you the errors within the form related to each unique field.
Drag and Drop Builder
You can build your own form with auto-generated code here at the React Hook Form Website.
You will be able to re-arrange using drag and drop, delete, and edit each field to start using this incredible plugin, without having to read any documentation, simply by copying that code.
You can easily build a form like this one in less than one minute!