كيفية بناء النماذج في React باستخدام مكتبة نماذج الخطاف المتفاعل
في هذه المقالة ، سوف نستكشف مكتبة شكل الخطاف التفاعلي.
سوف تتعلم كيفية استخدام هذه المكتبة ودمجها مع React. سنرى أيضًا سبب كونه خيارًا شائعًا لإنشاء نماذج بسيطة ومعقدة مع دعم إضافي للتعامل مع عمليات التحقق المعقدة.
هيا بنا نبدأ
العمل مع النماذج في React مهمة معقدة. ويصبح الأمر أكثر تعقيدًا عندما يزداد عدد حقول الإدخال جنبًا إلى جنب مع عمليات التحقق من الصحة.
ألق نظرة على الكود أدناه:
import React, { useState } from "react"; import "./styles.css"; export default function App() { const [state, setState] = useState({ email: "", password: "" }); const handleInputChange = (event) => { setState((prevProps) => ({ ...prevProps, [event.target.name]: event.target.value })); }; const handleSubmit = (event) => { event.preventDefault(); console.log(state); }; return ( Email Password Login ); }
إليك عرض Code Sandbox: //codesandbox.io/s/login-form-zjxs9.
في الكود أعلاه ، لدينا حقلا إدخال فقط ، وهما email
و password
، وزر إرسال.
كل حقل الإدخال لديه value
و onChange
أضاف معالج حتى نتمكن من تحديث الدولة على أساس إدخال المستخدم.
أضفنا أيضًا handleSubmit
طريقة تعرض البيانات التي تم إدخالها في النموذج إلى وحدة التحكم.
هذا يبدو جيدًا. ولكن ماذا لو احتجنا إلى إضافة عمليات التحقق مثل التحقق من صحة الحقل المطلوب ، والتحقق من الحد الأدنى للطول ، والتحقق من صحة كلمة المرور ، والتحقق من صحة حقل البريد الإلكتروني ، وكذلك عرض رسائل الخطأ المقابلة؟
سيصبح الرمز أكثر تعقيدًا وطولًا مع زيادة عدد حقول الإدخال وزيادة عمليات التحقق من صحتها.
هذا مطلب شائع جدًا في أي تطبيق. ذلك أن العمل بسهولة مع النماذج، وهناك العديد من المكتبات المتاحة مثل Formik
، redux-form
، react-final-form
، react-hook-form
وهلم جرا.
لكن react-hook-form
المكتبة التي تكتسب شعبية كبيرة .
فلنتعلم الآن لماذا وكيف نستخدمه. لذلك ، سننشئ تطبيق React جديدًا.
أنشئ مشروع React جديدًا عن طريق تشغيل الأمر التالي من المحطة:
npx create-react-app react-hook-form-demo
حالما يتم إنشاء المشروع، حذف كافة الملفات من src
مجلد وخلق فرص عمل جديدة index.js
و styles.css
الملفات داخل src
مجلد.
لتثبيت مكتبة النماذج ، قم بتنفيذ الأمر التالي من المحطة:
yarn add react-hook-form
كيفية إنشاء الصفحات الأولية
افتح src/index.js
الملف وأضف المحتوى التالي بداخله:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(, document.getElementById('root'));
افتح src/styles.css
الملف وأضف المحتوى من هنا بداخله.
الآن ، قم بإنشاء ملف جديد App.js
داخل src
المجلد بالمحتوى التالي:
import React from "react"; import "./styles.css"; export default function App() { return ( Email Password Login ); }
هنا ، أضفنا حقلي البريد الإلكتروني وكلمة المرور إلى النموذج.
إنشاء النموذج الأساسي باستخدام شكل رد فعل هوك
و react-hook-form
توفر المكتبة لديها useForm
هوك التي يمكننا استخدامها لعمل مع النماذج.
قم باستيراد useForm
الخطاف مثل هذا:
import { useForm } from 'react-hook-form';
استخدم useForm
الخطاف مثل هذا:
const { register, handleSubmit, errors } = useForm();
هنا،
- Register هي وظيفة يتم استخدامها كمرجع يوفره
useForm
الخطاف. يمكننا تخصيصه لكل حقل إدخال حتىreact-hook-form
يتمكن من تتبع التغييرات لقيمة حقل الإدخال. - handleSubmit هي الوظيفة التي يمكننا استدعاؤها عند إرسال النموذج
- سوف تحتوي الأخطاء على أخطاء التحقق من الصحة ، إن وجدت
الآن ، استبدل محتويات App.js
الملف بالمحتوى التالي:
import React from "react"; import { useForm } from "react-hook-form"; import "./styles.css"; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email Password Login ); }
في الكود أعلاه ، قدمنا مرجعًا لكل حقل إدخال حصلنا عليه من useForm
الخطاف.
ref={register}
أضفنا أيضًا وظيفة onSubmit التي تمرر إلى وظيفة handleSubmit.
لاحظ أنه لكل حقل إدخال ، قدمنا اسمًا فريدًا إلزاميًا حتى react-hook-form
يمكن تتبع البيانات المتغيرة.
عندما نرسل النموذج ، ستتعامل وظيفة handleSubmit مع إرسال النموذج. سيرسل المستخدم البيانات المدخلة إلى وظيفة onSubmit التي نسجلها في وحدة التحكم.
const onSubmit = (data) => { console.log(data); };
الآن ، ابدأ التطبيق عن طريق تشغيل yarn start
الأمر.

كما ترى ، عندما نرسل النموذج ، يتم عرض التفاصيل التي أدخلها المستخدم في وحدة التحكم.
أيضًا ، بالمقارنة مع الكود بدونه react-hook-form
(الذي رأيناه في بداية هذه المقالة) ، فإن هذا الرمز أبسط بكثير. هذا هو لأننا لم يكن لديك لإضافة value
و onChange
معالج للمساهمة في كل مجال وليس هناك حاجة لإدارة الدولة تطبيق أنفسنا.
كيفية إضافة عمليات التحقق من صحة إلى النموذج
الآن ، دعنا نضيف الحقل المطلوب والتحقق من الطول الأدنى لحقول الإدخال.
لإضافة التحقق من الصحة ، يمكننا تمريره إلى وظيفة التسجيل التي يتم تمريرها كمرجع لكل حقل إدخال مثل هذا:
نريد أيضًا عرض رسالة الخطأ إذا فشل التحقق من الصحة.
عندما يفشل التحقق من الصحة ، useForm
سيتم ملء كائن الأخطاء القادم من الحقول التي فشل التحقق من الصحة فيها.
افتح App.js
الملف واستبدل محتوياته بالمحتوى التالي:
import React from "react"; import { useForm } from "react-hook-form"; import "./styles.css"; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email {errors.email && errors.email.type === "required" && ( Email is required.
)} {errors.email && errors.email.type === "pattern" && ( Email is not valid.
)} Password {errors.password && errors.password.type === "required" && ( Password is required.
)} {errors.password && errors.password.type === "minLength" && ( Password should be at-least 6 characters.
)} Login ); }

هنا ، بالنسبة لحقل إدخال البريد الإلكتروني ، قدمنا عمليات التحقق المطلوبة ومطابقة الأنماط.
لذلك أثناء الكتابة في حقل إدخال البريد الإلكتروني ، سيتم تشغيل التحقق بمجرد إرسال النموذج.
إذا فشل التحقق من الصحة ، errors.email
فسيتم ملء الحقل الموجود داخل كائن الأخطاء بحقل النوع الذي استخدمناه لعرض رسالة الخطأ.
{errors.email && errors.email.type === "required" && ( Email is required.
)}
In the similar way, we have added the password field validation.
So as you can see, each input field is automatically focused if there is any validation error for the that input field when we submit the form.
Also, the form is not submitted as long as there is a validation error. You can see that the console.log
statement is only printed if the form is valid.
So using react-hook-form
reduced the amount of code that we have to write. The validation is also responsive, so once the field becomes valid, the error message goes away instantly.
But as the number of validations for each field increases, the conditional checks and error message code will still increase. So we can further refactor the code to make it even simpler.
Take a look at the below code:
import React from 'react'; import { useForm } from 'react-hook-form'; import './styles.css'; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email {errors.email && {errors.email.message}
} Password {errors.password && ( {errors.password.message}
)} Login ); }
In the code above, we have changed the email and password validation code.
For the email input field, we changed this previous code:
to the below new code:
Here, we’ve directly provided the error message we want to display while adding the validation itself.
So we no longer need to add extra checks for each validation. We are displaying the error message using the message property available inside the errors object for each input field.
{errors.email && {errors.email.message}
}
So by doing it this way, the code is further simplified which makes it easy to add extra validations in future.
Note that if there are validation errors, the onSubmit handler will not be executed and the corresponding input field will automatically be focused (which is a good thing).
How to Add a Custom Validation Method
You can even provide a custom validation for the input field by adding a validate
method. This is useful if you need to perform complex validations like this:
// validation function const validatePassword = (value) => { if (value.length < 6) { return 'Password should be at-least 6 characters.'; } else if ( !/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)(?=.*[[email protected]#$*])/.test(value) ) { return 'Password should contain at least one uppercase letter, lowercase letter, digit, and special symbol.'; } return true; }; // JSX

Now you know how to use react-hook-form
to create forms in React along with complex validations.
Why react-hook-form is better than the alternatives
Let’s look at some additional reasons that react-hook-form
should become your preferred choice for working with forms.
- Code complexity is less as compared to
formik
,redux-form
and other alternatives. react-hook-form
integrates well with theyup
library for schema validation so you can combine your own validation schemas.- The number of re-renders in the application is small compared to the alternatives.
- Mounting time is less as compared to the alternatives.
For the actual comparison metrics, read more here.
Conclusion
في هذه المقالة ، رأينا كيفية الاستخدام react-hook-form
ولماذا هو الخيار المفضل لدى العديد من المطورين لبناء نماذج بسيطة ومعقدة في React.
يمكنك العثور على الكود المصدري لـ GitHub لهذا التطبيق هنا.
إذا أعجبك هذا المقال ، فستحب أيضًا مقالاتي الأخرى.
اشترك في رسالتي الإخبارية الأسبوعية للانضمام إلى أكثر من 1000 مشترك آخرين للحصول على نصائح وحيل ومقالات مذهلة مباشرة في صندوق الوارد الخاص بك.