This is a quick example of how to build a dynamic form with validation in React with the React Hook Form library.

React Hook Form is a relatively new library for working with forms in React using React Hooks, I just stumbled across it recently and will be using it for my React projects going forward, I think it’s easier to use than the other options available and requires less code. For more info see https://react-hook-form.com.

The example form allows selecting the number of tickets to purchase and then entering the name and email of the person each ticket is for, both fields are required and the email field must contain a valid email address. The “Buy Tickets” button simply displays the form values in an alert popup if the form is valid, and the “Reset” button resets the form back to it’s initial state including the removal of all ticket name & email fields.

Styling of the example is all done with Bootstrap 4.5 CSS, for more info see https://getbootstrap.com/docs/4.5/getting-started/introduction/.

App Component with Dynamic React Hook Form

The example app component contains all the code for the dynamic form built with React Hook Form.

Form validation rules are defined with the Yup schema validation library and passed to the useForm() function of the React Hook Form library.

The useForm() hook function returns an object with methods for working with a form including registering inputs, handling form submit, resetting the form, displaying errors, watching for value changes and more, for a complete list see https://react-hook-form.com/api#useForm.

A watcher is created on the numberOfTickets select field to provide access to the current number of tickets and to trigger a for re-render when the number of tickets is changed. The ticketNumbers() function returns an array of ticket indexes (e.g. [0,1,2,3...]) based on the number of tickets selected and is used in the component template to render the dynamic form fields for each ticket.

#react #programming #developer

How to Build Dynamic Form with Validation in React Hook Form
57.30 GEEK