Tillitsdone
down Scroll to discover

Building Dynamic Forms with React Hook Form + TS

Learn how to create powerful, type-safe dynamic forms using React Hook Form and TypeScript.

Master form validation, state management, and best practices for modern web applications.
thumbnail

A serene abstract representation of flowing data streams featuring interweaving ribbons of bright orange and electric blue light against a stark black background captured from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Building a Dynamic Form with React Hook Form and TypeScript

Forms are an essential part of any modern web application, but managing form state and validation can quickly become complex. React Hook Form has emerged as a powerful solution, offering excellent TypeScript support and impressive performance. Today, we’ll explore how to build a dynamic, type-safe form that your users will love.

Why React Hook Form?

React Hook Form stands out for its minimal re-renders, lightweight bundle size, and seamless TypeScript integration. Unlike traditional form libraries, it uses uncontrolled components by default, leading to better performance and smoother user experience.

Abstract visualization of interconnected nodes featuring bright yellow geometric patterns floating in neutral white space shot from a 45-degree angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Setting Up Our Project

First, let’s install the necessary dependencies:

Terminal window
npm install react-hook-form zod @hookform/resolvers/zod

Next, let’s define our form schema using Zod:

import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
const userFormSchema = z.object({
username: z.string()
.min(3, 'Username must be at least 3 characters')
.max(20, 'Username cannot exceed 20 characters'),
email: z.string()
.email('Please enter a valid email'),
age: z.number()
.min(18, 'Must be at least 18 years old')
.max(100, 'Age cannot exceed 100'),
interests: z.array(z.string())
.min(1, 'Select at least one interest')
});
type UserFormData = z.infer<typeof userFormSchema>;

Building the Form Component

Let’s create a dynamic form that adapts to user input:

const DynamicForm = () => {
const {
register,
handleSubmit,
formState: { errors },
watch,
} = useForm<UserFormData>({
resolver: zodResolver(userFormSchema),
defaultValues: {
interests: [],
},
});
const onSubmit = (data: UserFormData) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<input
{...register('username')}
placeholder="Username"
className="form-input"
/>
{errors.username && (
<span className="text-red-500">{errors.username.message}</span>
)}
</div>
<div>
<input
{...register('email')}
placeholder="Email"
className="form-input"
/>
{errors.email && (
<span className="text-red-500">{errors.email.message}</span>
)}
</div>
<div>
<input
{...register('age', { valueAsNumber: true })}
type="number"
placeholder="Age"
className="form-input"
/>
{errors.age && (
<span className="text-red-500">{errors.age.message}</span>
)}
</div>
<button type="submit" className="btn-primary">
Submit
</button>
</form>
);
};

Advanced Features

React Hook Form provides powerful features for complex scenarios. Let’s explore some of them:

  1. Field Arrays: Perfect for dynamic form fields
const { fields, append, remove } = useFieldArray({
name: 'interests',
control,
});
  1. Watch: Monitor field changes in real-time
const watchUsername = watch('username');
  1. Form Context: Share form functionality across components
const FormProvider = useFormContext();

Ethereal cloud formations in bright electric blue and soft white swirling against a deep black sky photographed from below looking up high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Best Practices and Tips

  1. Always define your schema using Zod or similar libraries
  2. Utilize TypeScript’s type inference for better code completion
  3. Keep form logic separate from UI components
  4. Use error boundaries for better error handling
  5. Implement proper loading states for async operations

Conclusion

React Hook Form with TypeScript provides a robust foundation for building dynamic, type-safe forms. By leveraging its powerful features and following best practices, you can create forms that are both developer-friendly and user-friendly.

Abstract underwater scene with tropical fish in bright orange and neon blue colors swimming through geometric patterns of light captured from a side view perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg
Talk with CEO
Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.