Giới thiệu
Giả sử bạn có form KYC, section Address Info sẽ được lặp lại nhiều lần khi người dùng bấm Add.
Để quản lý dữ liệu Address phát sinh, chúng ta sử dụng useFieldArray
Ví dụ
Datatype và validation
Chúng ta cần khai báo lại Data type và validation trường hợp Address là 1 array
File types\formFields.ts//...
export interface AddressInfoData {
street: string;
city: string;
zipCode: string;
country: string;
}
export interface ComplexFormData {
userInfo: UserInfoData;
addresses: AddressInfoData[];//address -> addresses
}
Định nghĩa lại validation\FormFieldSchema.ts
import * as yup from 'yup';
const userInfoSchema = yup.object().shape({
firstName: yup.string()
.required("Họ không được để trống.")
.min(2, "Họ phải có ít nhất 2 ký tự."),
lastName: yup.string()
.required("Tên không được để trống.")
.min(2, "Tên phải có ít nhất 2 ký tự."),
email: yup.string()
.email("Email không đúng định dạng.")
.required("Email không được để trống."),
phone: yup.string()
.required("Số điện thoại không được để trống.")
.matches(/^[0-9]{10,11}$/, "Số điện thoại phải là 10 hoặc 11 chữ số."),
profileImage: yup.mixed<FileList>()
.test('fileRequired', 'Ảnh đại diện là bắt buộc.', (value) => {
return value && value.length > 0;
})
.test('fileType', 'Chỉ cho phép file ảnh.', (value) => {
if (!value || value.length === 0) return true;
const file = value[0];
return ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type);
})
.test('fileSize', 'Kích thước ảnh tối đa 5MB.', (value) => {
if (!value || value.length === 0) return true;
const file = value[0];
return file.size <= 5 * 1024 * 1024; // 5MB
}),
});
const addressInfoSchema = yup.object().shape({
street: yup.string()
.required("Số nhà, đường không được để trống."),
city: yup.string()
.required("Thành phố không được để trống."),
zipCode: yup.string()
.required("Mã bưu chính không được để trống.")
.matches(/^[0-9]{5,6}$/, "Mã bưu chính phải là 5 hoặc 6 chữ số."),
country: yup.string()
.required("Quốc gia không được để trống."),
});
export const complexFormValidationSchema = yup.object().shape({
userInfo: userInfoSchema,
addresses: yup.array()
.of(addressInfoSchema)
.min(1, 'At least one address is required')
.required('Thông tin địa chỉ là bắt buộc.')
});
Address field Config
import type { FormField } from './formFields';
export const addressInfoFields: FormField[] = [
{
label: "Street",
name: "street",
type: "text",
placeholder: "Enter street address",
},
{
label: "City",
name: "city",
type: "text",
placeholder: "Enter city",
},
{
label: "Zip Code",
name: "zipCode",
type: "text",
placeholder: "Enter zip code",
},
{
label: "Country",
name: "country",
type: "text",
placeholder: "Enter country",
},
];
Xây Dựng Component AddressInfo
Component này sẽ có nhiệm vụ hiển thị một block địa chỉ duy nhất. Component address sẽ nhận các props cần thiết từ component DynamicForm để đăng ký các field và hiển thị lỗi.
import React from "react";
import type { Control, FieldErrors, UseFormRegister } from "react-hook-form";
import type { AddressInfoData, ComplexFormData } from "../../types/formFields";
import { addressInfoFields } from "../../types/formFieldConfig";
interface AddressInfoProp {
index: number;
onRemove: (index: number) => void;
register: UseFormRegister<ComplexFormData>;
errors: FieldErrors<ComplexFormData>;
control: Control<ComplexFormData>;
}
type AddressFieldPath = `addresses.${number}.${keyof AddressInfoData}`;
const AddressInfo: React.FC<AddressInfoProp> = ({ index, onRemove, register, errors, control }) => {
const addressErrors = errors.addresses?.[index] as FieldErrors<AddressInfoData>
return <>
<h3>Address Info {index}</h3>
<div className="card mb-4">
<div className="card-header bg-info text-white">Address Information</div>
<div className="card-body">
{addressInfoFields.map((field) => {
const fieldPath = `addresses.${index}.${field.name}` as AddressFieldPath;
return (
<div key={field.name}>
<label htmlFor={field.name} className="form-label">{field.label}</label>
<input id={field.name}
type={field.type}
placeholder={field.placeholder}
// {...register(`addresses.${index}.${field.name}` as const)}
{...register(fieldPath)}
className="form-control"
/>
{addressErrors?.[field.name as keyof AddressInfoData] && (
<div className="text-danger mt-1">
{addressErrors[field.name as keyof AddressInfoData]?.message}
</div>
)}
</div>
)
})
}
</div>
</div>
</>
}
export default AddressInfo;
index: Vị trí của địa chỉ trong mảng
const addressErrors = errors.addresses?.[index] as FieldErrors<AddressInfoData>
Lấy đối tượng error cụ thể cho block address này dựa vào index
Xây dựng component DynamicForm.tsx
import { useFieldArray, useForm, type SubmitHandler } from 'react-hook-form';
import type { ComplexFormData } from '../../types/formFields';
import UserInfo from './UserInfo';
import { yupResolver } from '@hookform/resolvers/yup';
import { complexFormValidationSchema } from '../../validation/formSchema';
import AddressInfo from './AddressInfo';
const DynamicForm = () => {
const { register, handleSubmit, control, formState: { errors } } = useForm<ComplexFormData>({
resolver: yupResolver(complexFormValidationSchema),
defaultValues: {
userInfo: { firstName: '', lastName: '', email: '', phone: '', profileImage: null },
addresses: [{ street: '', city: '', zipCode: '', country: '' }],
}
});
const { fields, append, remove } = useFieldArray({
control,
name: 'addresses',
});
const onSubmit: SubmitHandler<ComplexFormData> = (data: ComplexFormData) => {
console.log("Form submitted:", data);
const profileImageFile = data.userInfo.profileImage?.[0];
if (profileImageFile) {
console.log("Image name:", profileImageFile.name);
console.log("Size of image:", profileImageFile.size, "bytes");
console.log("File type:", profileImageFile.type);
const formData = new FormData();
formData.append('firstName', data.userInfo.firstName);
formData.append('lastName', data.userInfo.lastName);
formData.append('email', data.userInfo.email);
formData.append('phone', data.userInfo.phone);
data.addresses.forEach((address, index) => {
formData.append(`addresses[${index}].street`, address.street);
formData.append(`addresses[${index}].city`, address.city);
formData.append(`addresses[${index}].zipCode`, address.zipCode);
formData.append(`addresses[${index}].country`, address.country);
});
if (profileImageFile) {
formData.append('profileImage', profileImageFile);
}
try {
alert('Data was sent!');
} catch (error) {
console.error(error);
}
}
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="container mt-5">
<h2 className="mb-4">Simple Dynamic Form</h2>
<UserInfo register={register} errors={errors} control={control} />
<hr className="my-4" />
<h3>Addresses</h3>
{fields.map((field, index) => (
<AddressInfo
key={field.id}
index={index}
onRemove={remove}
register={register}
control={control}
errors={errors}
/>
))}
<div className="mb-4">
<button
type="button"
onClick={() =>
append({ street: "", city: "", zipCode: "", country: "" })
} // Thêm một đối tượng AddressInfoData rỗng
>
Add Address
</button>
{errors.addresses?.message && (
<div className="alert alert-danger" role="alert">
{errors.addresses.message}
</div>
)}
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
);
}
export default DynamicForm;
Nhận xét
Đăng nhận xét