3rd Practical Class:
Forms
- React Inputs
- React Hook Form
- Controlled Inputs
- Form Validation
- Forms in our Quacker App
React Inputs
Controlled input - you provide:
value
: current input valueonChange
: called each time user changes value in input (typing, paste, ...)- new value is in
event.target.value
- new value is in
Disadvantages
- you must create a state and connect
value
&onChange
for each field - no built-in validation handling
- the whole form is re-rendered on every field value change
React Hook Form
- library for handling forms in React
- uses custom hooks and React context to connect the form fields
Custom Controlled Inputs
FormProvider
- context holding the form stateuseForm()
documentation - returns form methods passed toFormProvider
useController()
documentation - connects a single form field
Form Validation
- recommended to use a schema validation library
- pass a schema
resolver
touseForm()
- react-hook-form/resolvers - official resolvers of popular schema validation libraries
Advantage:
- all validation rules defined in one place
Yup
Forms in our Quacker App
Base Components
frontend/src/shared/hook-form/molecules/
- Form.js - combining
FormProvider
andform
- FormField.js - using Form Control components from Chakra UI
- Form.js - combining
Form Example with Validation
frontend/src/modules/auth/organisms/