Building React Forms with Ease Using React Hook Form, Zod and Shadcn
Dec 08, 2024 am 01:20 AMForms are something every developer encounters, whether as a user or on the developer side. They’re essential on most websites, but their complexity can vary wildly—from simple 3-field contact forms to giga-monster-t-rex, multi-page forms with 150 fields, dynamic validation, and asynchronous checks.
In this post, we’ll explore how React Hook Form, Zod, and Shadcn can be used to create an adaptable, developer-friendly solution that handles a wide range of form requirements with ease.
The form we’ll be building
Here’s the form we’ll be developing in this post. I plan on writing another post about an advanced use of forms that will have even more complexity as a follow-up, so stay tuned ?
Meet the tools
Let’s look at the stack we’ll use to build and manage our forms.
React and Wasp
- Framework: Wasp (full-stack framework for React, Node.js, and Prisma).
- Enables fast, efficient full-stack web development and deployment with React.
React Hook Form
- Lightweight library for crafting forms in React, mainly via its useForm hook.
- Handles form validation, error management, and offers flexible validation method and integration with various UI component libraries.
Zod
- TypeScript-first validation library for creating detailed, reusable validation schemas.
- Integrates with TypeScript types to keep validation unified and avoid duplication.
Shadcn/UI
- Collection of reusable UI components which are embedded directly in project, which allows developers to take only what they need and customize those components as well.
- Offers built-in support for React Hook Form and Zod.
Here’s an example snippet showcasing a form field in Shadcn library:
<FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input {...field} /> </FormControl> <FormMessage /> </FormItem> )} />
Even if you prefer using a different flavor of the stack, as long as you stick with React and RHF, this is still a valid example that will get you going.
Let’s build a simple user dashboard
The application we'll use to demonstrate basic forms is an admin panel with essential CRUD operations. It will include email and password authentication and consist of two pages: a main screen displaying a table of all users, and a user creation page, which will be the star of this article.
Our form will include validation to ensure users cannot submit it (i.e., create a new user) without meeting the specified requirements. The User object is an excellent candidate for validation examples, as it contains a variety of data types suitable for different validations: strings, dates (e.g., date of birth), email strings, and booleans (e.g., premium user status). The complete Prisma schema file is shown below.
<FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input {...field} /> </FormControl> <FormMessage /> </FormItem> )} />
To jumpstart our project, we’ll use a predefined Wasp template with TypeScript, called todo-ts. This template comes with ready-made components and routing for authentication, including login and signup screens. It also offers a solid example of how CRUD operations work in Wasp, ideal if you’re new to the framework. Additionally, we’ll leverage the new Wasp TypeScript SDK to manage our configuration, as it provides extended flexibility for customization.
Finding this article useful?
Wasp?team is working hard to create content like this, not to mention building a modern, open-source React/NodeJS framework.
The easiest way to show your support is just to star Wasp repo! ? But it would be greatly appreciated if you could take a look at the repository (for contributions, or to simply test the product). Click on the button below to give Wasp a star and show your support!
?? Thank You For Your Support ?
Putting it all together - Zod schema React Hook Form instance layout
To work with forms, we’ll start by defining a Zod validation schema. Our form has three data types: strings, a date, and a boolean. We’ll apply validation to most fields: name and surname are required, while email utilises the built-in e-mail validation. Zod simplifies validating common string types with built-in validations for different types, like emails, URLs, and UUIDs, which is helpful for our email field.
For additional validations, the date can’t be set to a future date, and the premiumUser field simply needs to be a boolean. Zod also provides default validation error messages, but these can be customized. For example, instead of name: z.string().min(1), we could specify name: z.string().min(1, 'Name is required').
<FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input {...field} /> </FormControl> <FormMessage /> </FormItem> )} />
Our form is managed by the useForm hook from React Hook Form, which provides extensive options for handling and validating form values, checking errors, and managing form state. To integrate our Zod validation schema, we’ll use a Zod resolver, allowing React Hook Form to apply the validations we defined earlier.
The form’s defaultValues are derived from the customer object. Since this component is used for both adding new customers and editing existing ones, we’ll pass the necessary data as input. For a new customer, some sensible default values are used; for existing customers, data is retrieved from the database. Apart from setting default values and determining whether to call createCustomer or updateCustomer, all other aspects of form handling remain the same.
model Customer { id Int @id @default(autoincrement()) name String surname String email String dateOfBirth DateTime premiumUser Boolean }
The final step is to create the form itself and assemble it in the TSX file. As shown earlier, this process is straightforward. Whether we’re using text inputs, date pickers, or checkboxes with Shadcn controls, we follow a similar structure:
- Start by creating the FormField element and setting its control, name, and render properties.
- The render property is key, as it contains the form element itself.
- Typically, we wrap everything in FormItem, add a FormLabel for the label, and place the controlled form element inside FormControl with the appropriate value and setter method.
- Finally, we include FormMessage below, which displays the Zod validation message if validation fails.
const formSchema = z.object({ name: z.string().min(1, { message: 'Name is required' }), surname: z.string().min(1, { message: 'Surname is required' }), email: z.string().email({ message: 'Invalid email address' }), dateOfBirth: z .date() .max(new Date(), { message: 'Date cannot be in the future' }), premiumUser: z.boolean(), });
If you’re curious to see the completed application, check out the GitHub repository here: GitHub Repo. I hope this article has made working with forms easier, and if you're interested in more form-related content, stay tuned for part two! In the next part, we'll dive into advanced patterns and validation techniques to enhance your applications.
Please consider starring Wasp on GitHub if you liked this post! Your support helps us continue making web development easier and smoother for everyone. ?
The above is the detailed content of Building React Forms with Ease Using React Hook Form, Zod and Shadcn. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

The main reasons for slow operation of DOM are the high cost of rearrangement and redrawing and low access efficiency. Optimization methods include: 1. Reduce the number of accesses and cache read values; 2. Batch read and write operations; 3. Merge and modify, use document fragments or hidden elements; 4. Avoid layout jitter and centrally handle read and write; 5. Use framework or requestAnimationFrame asynchronous update.
