• Home
  • React
  • React Hook Form – phương pháp quản lý form tối ưu cho dự án của bạn

React Hook Form – phương pháp quản lý form tối ưu cho dự án của bạn

Hầu hết trong các dự án Front-end ai cũng trải qua việc xử lý form, nếu làm theo cách thủ công sẽ tốn rất nhiều thời gian và rắc rối để xử lý. Vì thế trong bài viết này mình  sẽ giới thiệu tới các bạn một thư viện giúp chúng ta tiết kiệm thời gian cho việc quản lý form, đó là react hook form

React-hook-form là gì?

hiểu đơn giản thì react-hook-form là một thư viện giúp quản lý form tốt nhất hiện nay mà bạn nên dùng. Và sau đây mình sẽ giải thích rõ và demo code với react.

Cài đặt

				
					npm install react-hook-form
				
			
				
					yarn add react-hook-form
				
			

Ví dụ cơ bản

Sau đây tôi sẽ có 1 ví dụ cơ bản về React Hook Form để có giúp các bạn có thể hiểu về nội dung câu lệnh dùng để làm gì.

				
					import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, formState: { errors } } = useForm({
      criteriaMode: "all"
  });

  return (
    // Hàm handleSubmit sẽ validate trước khi gọi hàm onSubmit
    <form onSubmit={handleSubmit(onSubmit)}>

      // đăng kí input cho Hook vói tên email 
      <input defaultValue="test" {...register("email")} />

      // đăng kí thẻ input với React-Hook-Form với tên "password"
      // validate là required
      <input {...register("password", { required: true })} />

      // xử lý lỗi bằng <a href="https://fstack.io.vn/blog/lap-trinh-huong-doi-tuong-la-gi-mot-so-dac-trung-cua-oop/">đối tượng</a> errors được trả về từ useForm
      {errors.exampleRequired && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}


				
			

Khái niệm cần biết

useForm

Để làm việc với React-Hook-Form đầu tiên chúng ta cần khởi tạo useForm

Tham số truyền vào:

				
					 const { register, handleSubmit, formState: { errors } } = useForm({
      mode: 'onSubmit',
      reValidateMode: 'onChange',
      defaultValues: {},
      resolver: undefined,
      criteriaMode: "firstError",
})

				
			

Một vài tham số thường dùng để truyền vào useForm:

defaultValues: Thiết lập giá trị mặc định (lần đầu) cho form.

mode: có các giá trị onChange | onBlur | onSubmit | onTouched | all . Dùng để cấu hình chiến lược validate trước khi submit form.

resolver: hỗ trợ validate đối với thỉt-party (yup).

Giá trị trả về:


Register: là một trong những nội dung chính của react hook form, nó dùng để đăng kí component của bạn với hook.
ví dụ:
				
					function App() {
  const { register, handleSubmi, reset } = useForm();

  const onSubmit = (data) => {
      console.log(data);  // { eemail: ... }
      const data = gatDataService();
      reset(data);
  }

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input {...register("email", {
        // validate
        required: true

        // bắt sự kiện khi thay đổi giá trị input
        onChange: (e) => console.log(e) 
        // bắt sự kiện khi Blur chuột
        onBlur: (e) => console.log(e) 
        })} />        
        <input type="submit" />
      </form>
    </>
  );
}

				
			

handleSubmit: nó sẽ được thực hiện sau khi validate thành công. Như ví dụ trên nó sẽ gọi hàm onSubmit .

reset: dùng để đặt lại giá trị mặc định cho Form (thường dùng để sau khi call API chúng ta đặt lại giá trị mặc định cho Form).

 

Bài viết liên quan

Building a High-Converting Shopify Product Page: Design, Copy, and Psychology

Your Shopify product page is the digital storefront where potential customers decide whether to make a purchase. It’s…

ByByAuto Mation Dec 30, 2025

The Impact of Page Speed on Conversions: Optimizing Your Shopify Store for a Faster User Experience

In the fast-paced world of e-commerce, every second counts. A slow-loading Shopify store can be the difference between…

ByByAuto Mation Dec 29, 2025

Shopify Order Routing: How to Ship From Multiple Warehouses Efficiently

In today’s competitive e-commerce landscape, efficient order fulfillment is crucial for customer satisfaction and business success. For Shopify…

ByByAuto Mation Dec 29, 2025

Shopify SEO Beyond Keywords: Optimizing for Voice Search and Visual Discovery

In the ever-evolving landscape of e-commerce, staying ahead of the curve is paramount for Shopify store owners. While…

ByByAuto Mation Dec 29, 2025

Subscribe
Thông báo của
guest

0 Comments
Cũ nhất
Mới nhất Được bình chọn nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận

0
Rất mong nhận được suy nghĩ của bạn, vui lòng bình luận.x
()
x