| How to Type API Responses in React :👈 | 👉:How to Handle Optional Props in TypeScript |
How to Create Type-Safe Reusable Form Components |
How to Create Type-Safe Reusable Form Components in React with TypeScript
1. What Are Type-Safe Reusable Form Components?
In React applications, forms are used to collect user information such as names, email addresses, passwords, phone numbers, and addresses.
Instead of creating separate form controls for every page, we can build reusable components that work across the application.
TypeScript helps us make these components type-safe by ensuring that:
- Form fields receive the correct values.
- Event handlers use the correct event types.
- Form data follows the expected structure.
- Invalid property names and value types are detected during development.
- Reusable components work consistently across different forms.
Example: A common application might contain:
- Login Form
- Registration Form
- User Profile Form
- Product Form
- Employee Form
All these forms can reuse common components such as Input, TextArea, Select, Checkbox, and Button.
2. Create a Reusable Input Component
Let's start with a simple reusable input component.
React provides the InputHTMLAttributes type to reuse the standard HTML input properties.
import {
InputHTMLAttributes
} from "react";
type InputProps = InputHTMLAttributes<HTMLInputElement> & {
label: string;
error?: string;
};
function Input({
label,
error,
id,
...props
}: InputProps) {
return (
<div>
<label htmlFor={id}>
{label}
</label>
<input
id={id}
{...props}
/>
{error && (
<p role="alert">{error}</p>
)}
</div>
);
}
export default Input;
Using the component:
function LoginForm() {
return (
<form>
<Input
id="email"
label="Email"
type="email"
placeholder="Enter email"
/>
<Input
id="password"
label="Password"
type="password"
placeholder="Enter password"
/>
<button type="submit">
Login
</button>
</form>
);
}
Explanation:
InputHTMLAttributes<HTMLInputElement>provides standard HTML input properties such as type, placeholder, value, disabled, and required.labelis an additional required property for our reusable component.erroris an optional property for displaying validation messages....propsforwards the remaining input properties to the HTML input element.
3. Create a Reusable TextArea Component
We can use the same approach for a textarea component.
import {
TextareaHTMLAttributes
} from "react";
type TextAreaProps =
TextareaHTMLAttributes<HTMLTextAreaElement> & {
label: string;
error?: string;
};
function TextArea({
label,
error,
id,
...props
}: TextAreaProps) {
return (
<div>
<label htmlFor={id}>
{label}
</label>
<textarea
id={id}
{...props}
/>
{error && (
<p role="alert">{error}</p>
)}
</div>
);
}
export default TextArea;
Using the component:
<TextArea
id="description"
label="Description"
placeholder="Enter description"
rows={4}
/>
4. Create a Reusable Select Component
A select component allows users to choose an option from a dropdown.
import {
SelectHTMLAttributes
} from "react";
type SelectOption = {
label: string;
value: string;
};
type SelectProps =
Omit<
SelectHTMLAttributes<HTMLSelectElement>,
"children"
> & {
label: string;
options: SelectOption[];
error?: string;
};
function Select({
label,
options,
error,
id,
...props
}: SelectProps) {
return (
<div>
<label htmlFor={id}>
{label}
</label>
<select id={id} {...props}>
<option value="">
Select an option
</option>
{options.map(option => (
<option
key={option.value}
value={option.value}
>
{option.label}
</option>
))}
</select>
{error && (
<p role="alert">{error}</p>
)}
</div>
);
}
export default Select;
Using the component:
const countries = [
{ label: "India", value: "IN" },
{ label: "USA", value: "US" },
{ label: "UK", value: "UK" }
];
<Select
id="country"
label="Country"
options={countries}
required
/>
Here, Omit removes the standard children property because our component generates its own dropdown options.
5. Create a Reusable Checkbox Component
import {
InputHTMLAttributes
} from "react";
type CheckboxProps =
Omit<
InputHTMLAttributes<HTMLInputElement>,
"type"
> & {
label: string;
error?: string;
};
function Checkbox({
label,
error,
id,
...props
}: CheckboxProps) {
return (
<div>
<label htmlFor={id}>
<input
id={id}
type="checkbox"
{...props}
/>
{label}
</label>
{error && (
<p role="alert">{error}</p>
)}
</div>
);
}
export default Checkbox;
Using the component:
<Checkbox
id="terms"
label="I accept the terms and conditions"
required
/>
6. Type Form Data Using TypeScript
Reusable input components handle individual controls. We also need to define the structure of the complete form data.
Consider a registration form:
interface RegistrationForm {
name: string;
email: string;
password: string;
age: number;
country: string;
description: string;
acceptTerms: boolean;
}
This interface defines the expected structure of the registration form.
We can now use it with React's useState.
import { useState } from "react";
const [formData, setFormData] =
useState<RegistrationForm>({
name: "",
email: "",
password: "",
age: 18,
country: "",
description: "",
acceptTerms: false
});
TypeScript now checks that the form state follows the RegistrationForm structure.
7. Create a Type-Safe Generic Input Change Handler
Instead of creating a separate change handler for every input field, we can create one reusable handler.
function handleChange<K extends keyof RegistrationForm>(
field: K,
value: RegistrationForm[K]
) {
setFormData(previous => ({
...previous,
[field]: value
}));
}
Understanding the generic types:
keyof RegistrationFormrepresents all valid property names in the RegistrationForm interface.Krepresents one selected property name.RegistrationForm[K]represents the value type of that selected property.
For example:
handleChange("name", "John"); // Valid
handleChange("age", 25); // Valid
handleChange("acceptTerms", true); // Valid
handleChange("age", "Twenty"); // Type error
handleChange("unknown", "Value"); // Type error
This is a powerful TypeScript feature called a generic key-value relationship.
8. Build a Complete Registration Form
Now let's combine the reusable components and typed form state into one registration form.
import { useState } from "react";
interface RegistrationForm {
name: string;
email: string;
password: string;
age: number;
country: string;
description: string;
acceptTerms: boolean;
}
function Registration() {
const [formData, setFormData] =
useState<RegistrationForm>({
name: "",
email: "",
password: "",
age: 18,
country: "",
description: "",
acceptTerms: false
});
const [errors, setErrors] =
useState<Partial<Record<keyof RegistrationForm, string>>>({});
function handleChange<K extends keyof RegistrationForm>(
field: K,
value: RegistrationForm[K]
) {
setFormData(previous => ({
...previous,
[field]: value
}));
}
function handleSubmit(
event: React.FormEvent<HTMLFormElement>
) {
event.preventDefault();
const newErrors:
Partial<Record<keyof RegistrationForm, string>> = {};
if (!formData.name.trim()) {
newErrors.name = "Name is required";
}
if (!formData.email.trim()) {
newErrors.email = "Email is required";
}
if (!formData.password) {
newErrors.password = "Password is required";
}
if (!formData.country) {
newErrors.country = "Please select a country";
}
if (!formData.acceptTerms) {
newErrors.acceptTerms = "Please accept the terms";
}
setErrors(newErrors);
if (Object.keys(newErrors).length === 0) {
console.log("Submitted data:", formData);
}
}
return (
<form onSubmit={handleSubmit}>
<Input
id="name"
label="Name"
value={formData.name}
onChange={event =>
handleChange("name", event.target.value)
}
error={errors.name}
/>
<Input
id="email"
label="Email"
type="email"
value={formData.email}
onChange={event =>
handleChange("email", event.target.value)
}
error={errors.email}
/>
<Input
id="password"
label="Password"
type="password"
value={formData.password}
onChange={event =>
handleChange("password", event.target.value)
}
error={errors.password}
/>
<Input
id="age"
label="Age"
type="number"
value={formData.age}
onChange={event =>
handleChange("age", Number(event.target.value))
}
/>
<Select
id="country"
label="Country"
options={[
{ label: "India", value: "IN" },
{ label: "USA", value: "US" },
{ label: "UK", value: "UK" }
]}
value={formData.country}
onChange={event =>
handleChange("country", event.target.value)
}
error={errors.country}
/>
<TextArea
id="description"
label="Description"
value={formData.description}
onChange={event =>
handleChange("description", event.target.value)
}
/>
<Checkbox
id="terms"
label="Accept terms and conditions"
checked={formData.acceptTerms}
onChange={event =>
handleChange("acceptTerms", event.target.checked)
}
error={errors.acceptTerms}
/>
<button type="submit">
Register
</button>
</form>
);
}
What happens here?
- The RegistrationForm interface defines all form fields and their types.
useState<RegistrationForm>stores the complete form data.- The generic
handleChangefunction updates any valid field while preserving its value type. - Reusable Input, Select, TextArea, and Checkbox components render the controls.
- The submit handler checks the form values and displays validation errors.
- The form data is submitted only when the basic validation checks pass.
9. Understand Partial, Record, and keyof
These TypeScript utility types are particularly useful when building reusable forms.
Partial<T>
Partial makes all properties of a type optional.
interface User {
name: string;
email: string;
age: number;
}
type UserErrors = Partial<User>;
Now we can create an object containing only the fields that have errors.
const errors: Partial<User> = {
email: "Invalid email address"
};
keyof
keyof creates a union of an object's property names.
type UserFields = keyof User;
// Result:
// "name" | "email" | "age"
Record<K, V>
Record creates an object type with specified keys and value types.
type UserErrors = Record<keyof User, string>;
This requires an error string for every property. To make the error fields optional, combine it with Partial:
type UserErrors =
Partial<Record<keyof User, string>>;
10. Using React Hook Form for Larger Applications
For complex forms, manually managing every field, validation rule, and error can become difficult.
React Hook Form is a popular library for managing form state and validation.
It also supports TypeScript generics.
Install the library:
npm install react-hook-form
Example:
import { useForm, SubmitHandler } from "react-hook-form";
interface LoginForm {
email: string;
password: string;
}
function Login() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm<LoginForm>();
const onSubmit: SubmitHandler<LoginForm> = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>Email</label>
<input
type="email"
{...register("email", {
required: "Email is required"
})}
/>
{errors.email && (
<p>{errors.email.message}</p>
)}
<label>Password</label>
<input
type="password"
{...register("password", {
required: "Password is required"
})}
/>
{errors.password && (
<p>{errors.password.message}</p>
)}
<button type="submit">
Login
</button>
</form>
);
}
Important points:
useForm<LoginForm>()defines the expected form data structure.register()connects an input to the form.- TypeScript checks field names against the LoginForm interface.
handleSubmit()handles form submission.SubmitHandler<LoginForm>types the submit callback.errorscontains validation information for the form fields.
11. Best Practices
- Create reusable Input, Select, TextArea, Checkbox, and Button components.
- Use React's built-in HTML attribute types instead of manually defining every standard property.
- Define a separate interface or type for each form's data structure.
- Use generics when creating reusable form controls and change handlers.
- Use
keyofto restrict field names to valid form properties. - Use
Partialfor optional validation errors. - Use controlled inputs when the component needs to manage values through React state.
- Keep validation logic separate from reusable presentation components where practical.
- Use a form library such as React Hook Form for complex forms.
- Validate important data on the server as well. Client-side validation alone is not sufficient.
- Use unique IDs and connect labels to their corresponding inputs.
- Use appropriate HTML input types and accessible error messages.
12. Common Mistakes
1. Using any for Form Data
Avoid:
const [formData, setFormData] = useState<any>({});
Better:
const [formData, setFormData] =
useState<RegistrationForm>({
name: "",
email: "",
password: "",
age: 18,
country: "",
description: "",
acceptTerms: false
});
2. Forgetting to Convert Number Input Values
HTML input values are strings, including values from inputs with type="number".
Avoid:
handleChange("age", event.target.value);
Better:
handleChange("age", Number(event.target.value));
3. Using the Wrong Event Property
For a normal text input, use event.target.value. For a checkbox, use event.target.checked.
4. Making Every Form Component Handle Business Logic
A reusable Input component should primarily handle rendering and input-related properties. Form submission and business validation should normally remain in the parent form or a dedicated form-management layer.
13. Interview Questions and Answers
Q1. What are reusable form components in React?
Reusable form components are common UI controls such as Input, Select, TextArea, and Checkbox that can be used across multiple forms.
Q2. How do you make a React form component type-safe?
Use TypeScript interfaces or types for props and form data, and use the appropriate React event and HTML attribute types.
Q3. What is InputHTMLAttributes in React?
It is a React TypeScript type that provides standard HTML input properties such as type, placeholder, value, disabled, and required.
Q4. What is the purpose of keyof?
keyof creates a union of the property names of a type. It helps restrict form field names to valid properties.
Q5. What is the purpose of Partial?
Partial<T> makes all properties of a type optional. It is useful for representing validation errors because only some fields may contain errors.
Q6. What is a generic change handler?
A generic change handler updates different form fields while ensuring that each field receives the correct value type.
Q7. What is the difference between controlled and uncontrolled inputs?
A controlled input gets its value from React state and updates through an event handler. An uncontrolled input stores its current value in the DOM and can be accessed using a ref.
Q8. Why use React Hook Form?
React Hook Form simplifies form state management, validation, and submission. It also provides TypeScript support through generic form types.
Q9. Why should we validate data on the server?
Client-side validation can be bypassed. Server-side validation is necessary to protect application data and enforce business rules.
Q10. Can generics be used in reusable form components?
Yes. Generics allow reusable components and handlers to support different form data structures while maintaining type safety.
14. Key Takeaways
- Build common form controls as reusable React components.
- Use TypeScript interfaces to define form data structures.
- Use React HTML attribute types to inherit standard input properties.
- Use generics and
keyofto create type-safe change handlers. - Use
PartialandRecordto represent validation errors. - Use controlled inputs when React state manages the form values.
- Use React Hook Form for larger and more complex forms.
- Always validate important form data on the server.
Remember: A good reusable form architecture separates UI components, form state, validation, and business logic. TypeScript ensures that these parts work together with the correct data types.
| How to Type API Responses in React :👈 | 👉:How to Handle Optional Props in TypeScript |
Comments and Discussion