Skip to content

Commit 16c6187

Browse files
authored
create a new post (#2379)
1 parent ca86b09 commit 16c6187

File tree

7 files changed

+188
-0
lines changed

7 files changed

+188
-0
lines changed

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
---
2+
title: 'Building React Forms with Ease Using React Hook Form, Zod and Shadcn'
3+
authors: [martinovicdev]
4+
image: /img/forms/banner.webp
5+
tags: [webdev, wasp, react, forms]
6+
---
7+
8+
import Link from '@docusaurus/Link';
9+
import useBaseUrl from '@docusaurus/useBaseUrl';
10+
11+
import InBlogCta from './components/InBlogCta';
12+
import WaspIntro from './_wasp-intro.md';
13+
import ImgWithCaption from './components/ImgWithCaption'
14+
15+
Forms 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.
16+
17+
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.
18+
19+
![david and victoria meme](/img/forms/meme.webp)
20+
21+
## The form we’ll be building
22+
23+
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 😃
24+
25+
![example form](/img/forms/form.png)
26+
27+
## Meet the tools
28+
29+
Let’s look at the stack we’ll use to build and manage our forms.
30+
31+
### **React and Wasp**
32+
33+
- Framework: [**Wasp**](https://github.com/wasp-lang/wasp) (full-stack framework for React, Node.js, and Prisma).
34+
- Enables fast, efficient full-stack web development and deployment with React.
35+
36+
### **React Hook Form**
37+
38+
- Lightweight library for crafting forms in React, mainly via its `useForm` hook.
39+
- Handles form validation, error management, and offers flexible validation method and integration with various UI component libraries.
40+
41+
### **Zod**
42+
43+
- TypeScript-first validation library for creating detailed, reusable validation schemas.
44+
- Integrates with TypeScript types to keep validation unified and avoid duplication.
45+
46+
### **Shadcn/UI**
47+
48+
- 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.
49+
- Offers built-in support for React Hook Form and Zod.
50+
51+
Here’s an example snippet showcasing a form field in Shadcn library:
52+
53+
```tsx
54+
<FormField
55+
control={form.control}
56+
name="name"
57+
render={({ field }) => (
58+
<FormItem>
59+
<FormLabel>Name</FormLabel>
60+
<FormControl>
61+
<Input {...field} />
62+
</FormControl>
63+
<FormMessage />
64+
</FormItem>
65+
)}
66+
/>
67+
```
68+
69+
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.
70+
71+
## Let’s build a simple user dashboard
72+
73+
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.
74+
75+
![example data](/img/forms/data.png)
76+
77+
![example form](/img/forms/form.png)
78+
79+
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.
80+
81+
```sql
82+
model Customer {
83+
id Int @id @default(autoincrement())
84+
name String
85+
surname String
86+
email String
87+
dateOfBirth DateTime
88+
premiumUser Boolean
89+
}
90+
```
91+
92+
To jumpstart our project, we’ll use a predefined [Wasp template](https://wasp-lang.dev/docs/project/starter-templates) 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.
93+
94+
### Finding this article useful?
95+
96+
[Wasp](https://wasp.sh/) team is working hard to create content like this, not to mention building a modern, open-source React/NodeJS framework.
97+
98+
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](https://github.com/wasp-lang/wasp) (for contributions, or to simply test the product). Click on the button below to give Wasp a star and show your support!
99+
100+
![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axqiv01tl1pha9ougp21.gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axqiv01tl1pha9ougp21.gif)
101+
102+
<div className="cta">
103+
<a href="https://github.com/wasp-lang/wasp" target="_blank" rel="noopener noreferrer">
104+
⭐️ Thank You For Your Support 💪
105+
</a>
106+
</div>
107+
108+
## Putting it all together - Zod schema + React Hook Form instance + layout
109+
110+
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.
111+
112+
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')`.
113+
114+
115+
116+
```tsx
117+
const formSchema = z.object({
118+
name: z.string().min(1, { message: 'Name is required' }),
119+
surname: z.string().min(1, { message: 'Surname is required' }),
120+
email: z.string().email({ message: 'Invalid email address' }),
121+
dateOfBirth: z
122+
.date()
123+
.max(new Date(), { message: 'Date cannot be in the future' }),
124+
premiumUser: z.boolean(),
125+
});
126+
```
127+
128+
Our form is managed by the `useForm` hook from [React Hook Form](https://react-hook-form.com/docs/useform), 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.
129+
130+
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.
131+
132+
```tsx
133+
type FormData = z.infer<typeof formSchema>
134+
const form = useForm<FormData>({
135+
resolver: zodResolver(formSchema),
136+
defaultValues: customer,
137+
});
138+
```
139+
140+
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:
141+
142+
- Start by creating the `FormField` element and setting its `control`, `name`, and `render` properties.
143+
- The `render` property is key, as it contains the form element itself.
144+
- 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.
145+
- Finally, we include `FormMessage` below, which displays the Zod validation message if validation fails.
146+
147+
![form with errors](/img/forms/form-error.png)
148+
149+
```tsx
150+
151+
// Defining form schema
152+
const formSchema = z.object({
153+
dateOfBirth: z.date().max(new Date(), {
154+
message: 'Date of birth cannot be today, or in the future',
155+
}),
156+
});
157+
158+
// Defining form
159+
const form = useForm<FormData>({
160+
resolver: zodResolver(formSchema),
161+
defaultValues: defaultValues,
162+
});
163+
164+
// Creating form control
165+
<FormField
166+
control={form.control}
167+
name="dateOfBirth"
168+
render={({ field }) => (
169+
<FormItem className="flex flex-col">
170+
<FormLabel>Date of birth</FormLabel>
171+
<FormControl>
172+
<DatePicker date={field.value} setDate={field.onChange} />
173+
</FormControl>
174+
<FormMessage />
175+
</FormItem>
176+
)}
177+
/>
178+
```
179+
180+
If you’re curious to see the complete application, check out the GitHub repository here: [GitHub Repo](https://github.com/martinovicdev/wasp-form-tutorial). 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.
181+
182+
Please consider starring [**Wasp**](https://github.com/wasp-lang/wasp) on GitHub if you liked this post! Your support helps us continue making web development easier and smoother for everyone. 🐝

web/static/img/forms/banner.webp

450 KB
Binary file not shown.

web/static/img/forms/data.png

44.5 KB
Loading

web/static/img/forms/form-error.png

46.8 KB
Loading

web/static/img/forms/form.png

53.8 KB
Loading

web/static/img/forms/meme.webp

17.2 KB
Binary file not shown.

0 commit comments

Comments
 (0)