Với Formik bạn có thể tạo các form dữ liệu phức tạp hơn cho react app của mình. Ví dụ, trong một biểu mẫu đăng ký tài khoản, bạn cần:
- Kiểm tra email hợp lệ
- Mật khẩu phải có 8 ký tự, trong đó tối thiểu 1 chữ cái thường, 1 chữ cái hoa, 1 số, 1 ký tự đặc biệt.
- Ngoài text input, sử dụng cả date, dropdown và checkbox.
- Submit toàn bộ thông tin của form theo dạng json.
Trước khi bắt đầu, bạn có thể tham khảo bài trước: ReactJS Bài 8: Kiểm tra dữ liệu đầu vào với Yup và Formik
Xem mục lục toàn bộ khoá học: Học lập trình ReactJS; khoá học ReactJS cơ bản
Khai báo giá trị ban đầu
Khai báo các trường giá trị cho field của form, với giá trị khởi tạo:
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as yup from 'yup';
import axios from 'axios';
const initialValues = {
name: '',
email: '',
password: '',
dob: '',
gender: '',
interests: [],
comments: ''
};
Tạo validation schema
Dùng Validation Schema để kiểm tra sự hợp lệ của dữ liệu mà người sử dụng nhập:
const validationSchema = yup.object().shape({
name: yup.string().required('Please enter your name'),
email: yup.string().email('Please enter a valid email').required('Please enter your email'),
password: yup
.string()
.matches( /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/, 'Password must contain at least 8 characters, including at least 1 lowercase letter, 1 uppercase letter, 1 special symbol, and 1 digit'
)
.required('Please enter a password'),
dob: yup.date().required('Please enter your date of birth'),
gender: yup.string().required('Please select your gender'),
interests: yup.array().min(1, 'Please select at least one interest'),
});
Tạo form component
Dùng formik để thiết lập biểu mẫu với các trường cần thiết:
const ComplexForm = () => {
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
<Form>
<div>
<label htmlFor="name">Name:</label>
<Field type="text" id="name" name="name" />
<ErrorMessage name="name" component="div" className="error" />
</div>
<div>
<label htmlFor="email">Email:</label>
<Field type="email" id="email" name="email" />
<ErrorMessage name="email" component="div" className="error" />
</div>
<div>
<label htmlFor="password">Password:</label>
<Field type="password" id="password" name="password" />
<ErrorMessage name="password" component="div" className="error" />
</div>
<div>
<label htmlFor="dob">Date of Birth:</label>
<Field type="date" id="dob" name="dob" />
<ErrorMessage name="dob" component="div" className="error" />
</div>
<div>
<label htmlFor="gender">Gender:</label>
<Field as="select" id="gender" name="gender">
<option value="">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</Field>
<ErrorMessage name="gender" component="div" className="error" />
</div>
<div>
<label>Interests:</label>
<div>
<label>
<Field type="checkbox" name="interests" value="reading" />
Reading
</label>
<label>
<Field type="checkbox" name="interests" value="sports" />
Sports
</label>
<label>
<Field type="checkbox" name="interests" value="music" />
Music
</label>
</div>
<ErrorMessage name="interests" component="div" className="error" />
</div>
<div>
<label htmlFor="comments">Comments:</label>
<Field as="textarea" id="comments" name="comments" />
<ErrorMessage name="comments" component="div" className="error" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
);
};
export default ComplexForm;
Cuối cùng, khi submit, post toàn bộ các giá trị của for ở dạng json lên api:
const handleSubmit = async (values) => { try { const response = await axios.post('/api/register', values); console.log(response.data); // Handle the response from the API } catch (error) { console.error(error); } };
Vậy là bạn đã học cách tạo 1 form biểu mẫu phức tạp với React sử dụng formik. Nếu thấy khoá học hữu ích, hãy cho mình 1 share nhé. Bạn cũng có thể để lại comment trên Facebook của Bệ Phóng Việt để chúng tôi tiếp tục nâng cấp nội dung của mình được tốt hơn.

