Building a Dynamic Form with React Hook Form and Typescript

afagh fth
5 min readJun 14, 2024

--

Hi guys 👋🏻

Let’s have a look at creating a dynamic form using React Hook Form! In this story, I’ll walk you through the process step-by-step, ensuring you understand every detail and feel confident in building your own forms. Meanwhile, I hope you are excited to use TypeScript and Tailwind as well.😁

Introduction to React Hook Form

React Hook Form is a powerful library for managing forms in React. It simplifies form validation, data handling, and integration with external libraries. With React Hook Form, you can create dynamic forms that are both user-friendly and easy to maintain. And for a lazy girll like me, what’s better than not having to use useState over and over again! 🫠

Let’s Start by Setting Up the Project

Before diving into the implementation details, it’s essential to set up our development environment properly. Here’s how to get started:

  • Create a new React project using Create React App with TypeScript template:
npx create-react-app my-form-app --template typescript cd my-form-app
  • Install React Hook Form, a powerful library for managing form state and validation in React:
npm install react-hook-form

What the Heck is React Hook Form? 🤔🙄

In short, React Hook Form is a library that optimizes form handling in React applications by minimizing re-renders and improving performance (now you might wonder how! ). It follows the “controlled components” approach, where form elements maintain their state through React state and are controlled by React Hook Form’s custom hooks. This approach ensures that form inputs remain lightweight and fast, even with complex validations! 🫣

Dont know about you, but I would be confused by “controlled components” so let’s talk about that first:
In React, controlled components are a fundamental concept for managing form elements and their state. So this is what controlled components are and why they are crucial in React development:

  • Definition: Controlled components refer to form elements (like <input>, <textarea>, <select>, etc.) whose value is controlled by React state. Instead of the DOM storing the form element’s state, React manages and controls the element’s state through its state management system. Pretty cool! 🥶
  • State Management: Controlled components rely on two main props: value and onChange. The value prop specifies the current value of the form element, while the onChange prop is a callback function that updates the component’s state whenever the user interacts with the form element (like typing in an input field).
  • Predictability: Since React controls the state and updates, developers can anticipate and control component behavior more easily, enhancing predictability and maintainability. And you will get that at your first try! 😉

Now, let’s explore why React Hook Form is a powerful library for managing forms in React applications:

Purpose:

React Hook Form (RHF) is designed to make form handling simple, efficient, and performant in React applications. It’s basically the use of controlled components plus some additional features for form validation, error handling, and more.

Core Concepts:

  • Hook-Based: It works on sholders of hooks (useForm, useController, etc.) to manage form state and validation rules. This aligns with React’s functional component paradigm, ensuring that form logic remains modular.
  • Minimal Re-renders: Unlike traditional form libraries that may trigger re-renders with every keystroke, RHF optimizes performance by reducing unnecessary re-renders. It achieves this through efficient state management and event handling. ( Now this would be intrestiong for whole an other subject 👀)
  • Validation: RHF provides validation, allowing developers to define thie rules directly within the component. Validation errors are seamlessly integrated into the form state, making it straightforward to display error messages and styles based on validation outcomes.

Benefits

  • Simplicity: RHF simplifies complex form handling tasks, such as nested forms or dynamic form fields, through intuitive APIs and hooks.
  • Performance: By minimizing re-renders and optimizing event handling, RHF ensures that form interactions remain smooth and responsive, even with large and complex forms.
  • Flexibility: Developers have the flexibility to customize form behavior and validation rules according to application requirements, without being tied to a rigid form structure imposed by the library.

Creating Reusable Input Components

Now that we have an simple undrestanding on what is react hook form, it’s time to start our form by creating inputs. Let’s create two input components: TextInput and DateInput.

lets strart TextInput component. first we importControl and useController from react-hook-form to control and manage the form inputs.

import React from 'react';
import { Control, useController } from 'react-hook-form';

And each input will get some data as props so we need a template for props of our component :

interface TextInputProps {
label: string; //The label text for the input field.
name: string; //The name attribute for the input field, used to identify the field in the form.
control: Control<any>; //The control object from react-hook-form for managing the input state.
rules?: object; //(optional) Validation rules for the input field.
type?: string; //(optional) The type of the input (default is 'text').
textarea?: boolean; // (optional): Boolean indicating if the input should be a textarea (default is false)
}

Just a reminder for myself ! I can use “optional chaining operator” (:?) to step up my code😋

const TextInput: React.FC<TextInputProps> = ({ label, name, control, rules, type = 'text', textarea = false }) => {
  • This is a functional component defined using TypeScript with the React.FC type and TextInputProps interface.

And now we are going to use useController, a custom hook from react-hook-form that binds the input to the form state.

const {
field: { onChange, onBlur, value, ref },
fieldState: { error },
} = useController({
name,
control,
rules,
});

And bibbidi bobbidi boo! 🪄 we’ll have this ready to use component :

Now all we have to do to use it in our form component:

You can see the complete code and work with it here : 💎Dynamic Form with React Hook Form💎

Just like i said, easy and fun! But not so fast. althogh this is a great way to handle forms its not alwasy a solid way like When we have Simple Forms Without Complex Logic, Forms with Heavy Customization and Styling Needs, Global Form State Management Needs or you have a Specific Performance Considerations. over all, always look for the best solution for your own scenario.

Conclusion 😪

And there you have it! We’ve just walked through creating a dynamic form using React Hook Form, TypeScript, and Tailwind. From setting up the project to understanding controlled components and creating reusable input components, you’re now well-equipped to build sophisticated forms in your React applications. Remember, the right tool and approach depend on your specific needs, so always consider your project’s requirements before diving in.

Happy coding, and may your forms always be user-friendly and bug-free! 🎉

--

--