Forms

Essential React

Different Form Tags

  • input / textarea
  • select
  • checkbox
  • radio

input / textarea

select

checkbox

radio

Controlled vs. Uncontrolled

Controlled

  • Form Data is handled by a React component
  • Change Event → State Update → Re-Render
  • For example,
    • on a keystroke
    • when selecting an option form a Dropdown

Uncontrolled

  • Form Data is handled by the DOM
  • State is updated only onBlur/onSubmit -> prevents needless re-renders
  • But, sometimes controlled fields are unavoidable
    • React-Select
    • Material-UI
To leverage uncontrolled form fields, using a library is advised

Demo

Controlled Form
vs.
Uncontrolled Form

Form Libraries

Form handling can be quite repetitive, the usage of a helper library should therefore be considered.

  • React Hook Form (Uncontrolled)
  • Formik (Controlled)

React Hook Form

React Hook Form is enabling you to easily set and update form state as well as execute validation with adequate error-handling.

Exercise

  1. Create a form using react-hook-form
    npm i react-hook-form
  2. Allow the user to enter their name & e-mail address
  3. Validate the inputs and display an error if necessary
  4. Log the result of the form submisson to the console

Exercise: Stretch Goal

Look at what validations register() supports and try to validate the e-mail address input as accurately as possible.

Solution (Name Input)

Solution (E-Mail Input)

Recap

We learned…

  • How to work with basic form controls
  • What Controlled and Uncontrolled Forms are
  • How to use a form library

Questions?