การตั้งค่า react-hook-form ร่วมกับ Controller
ติดตั้ง react-hook-form ใช้ useForm เพื่อสร้างอินสแตนซ์ของฟอร์ม และครอบ TextInput แต่ละรายการด้วย Controller เพื่อลงทะเบียนและรับ onChange/onBlur
การตั้งค่า react-hook-form ร่วมกับ Controller เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why react-hook-form?
react-hook-form is a performant, flexible library for building forms in React and React Native. Unlike manually wiring every input to useState, react-hook-form uses uncontrolled inputs to minimize re-renders. It integrates validation, error handling, and form submission into a single coherent API, and it works seamlessly with any UI component library through the Controller wrapper.
Installing react-hook-form
Install react-hook-form from npm. It has no dependencies and works with any React version 16.8+. No special configuration is needed — import its hooks and components directly into your React Native components after installation.
npm install react-hook-formCreating a Form Instance with useForm
Call useForm() at the top of your component to create a form instance. It returns several utilities: control (for wiring inputs via Controller), handleSubmit (for form submission), formState.errors (for displaying validation errors), and reset (to clear all fields). Pass default values to useForm to pre-populate the form.
import { useForm } from 'react-hook-form';
interface LoginForm {
email: string;
password: string;
}
export default function LoginScreen() {
const {
control,
handleSubmit,
formState: { errors },
reset,
} = useForm<LoginForm>({
defaultValues: { email: '', password: '' },
});
}Wrapping TextInput with Controller
In React Native, inputs are controlled components that need to be wrapped in Controller so react-hook-form can manage their values. Pass the control object, the field name, and a render prop. The render prop receives field which contains value, onChange, and onBlur to wire to the TextInput.
import { Controller } from 'react-hook-form';
<Controller
control={control}
name='email'
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
onBlur={onBlur}
placeholder='Email'
keyboardType='email-address'
autoCapitalize='none'
/>
)}
/>Adding Validation Rules
Pass a rules prop to Controller to define validation constraints. The required rule marks a field as mandatory, minLength enforces a minimum character count, maxLength caps input length, and pattern validates against a regex. Each rule takes an object with a value and a message string shown when the rule fails.
<Controller
control={control}
name='email'
rules={{
required: { value: true, message: 'Email is required' },
pattern: {
value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
message: 'Enter a valid email address',
},
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput value={value} onChangeText={onChange} onBlur={onBlur} />
)}
/>Displaying Field Errors
After Controller validates a field, any error is available in formState.errors[fieldName]. Access its message property and render it below the input in a red Text component. Errors only appear after the field has been touched (onBlur) or after the first submit attempt, preventing premature error messages.
<Controller
control={control}
name='email'
rules={{ required: 'Email is required' }}
render={({ field: { onChange, onBlur, value } }) => (
<View>
<TextInput
value={value}
onChangeText={onChange}
onBlur={onBlur}
style={[styles.input, errors.email && styles.inputError]}
/>
{errors.email && (
<Text style={styles.errorText}>{errors.email.message}</Text>
)}
</View>
)}
/>Handling Form Submission with handleSubmit
Wrap your submit handler with handleSubmit. react-hook-form will run all validation rules first; if any field is invalid, it populates formState.errors and does not call your handler. If all fields are valid, your handler receives a typed object containing all field values — ready to send to an API.
async function onSubmit(data: LoginForm) {
console.log('Submitting:', data.email, data.password);
try {
await authApi.login(data.email, data.password);
navigation.replace('Home');
} catch (err) {
Alert.alert('Login Failed', 'Invalid email or password.');
}
}
<Button title='Log In' onPress={handleSubmit(onSubmit)} />Password Field Configuration
For password fields, set secureTextEntry to hide the typed characters and configure an appropriate keyboard type. Wire the field to Controller exactly like the email field. Many apps also add a 'show/hide' icon button that toggles secureTextEntry via local state — this improves accessibility for users with typos.
<Controller
control={control}
name='password'
rules={{
required: 'Password is required',
minLength: { value: 8, message: 'Password must be at least 8 characters' },
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
onBlur={onBlur}
secureTextEntry
placeholder='Password'
/>
)}
/>Using watch to Observe Field Values
The watch function returned by useForm lets you subscribe to a field's current value and react to changes in real time. A common use case is a 'confirm password' field that validates its value matches the password field. Pass a field name to watch and use the returned value in the confirm field's validate rule.
const { control, handleSubmit, watch, formState: { errors } } = useForm<RegisterForm>();
const password = watch('password');
<Controller
control={control}
name='confirmPassword'
rules={{
validate: (value) =>
value === password || 'Passwords do not match',
}}
render={({ field }) => <TextInput {...field} secureTextEntry />}
/>Resetting the Form
Call reset() to clear all field values and errors, returning the form to its default values. You can also pass a new set of values to reset({ email: 'prefilled@example.com' }) to re-initialize the form with different defaults, which is useful for edit-profile forms that pre-populate with existing user data.
// Clear after successful submit:
async function onSubmit(data: LoginForm) {
await api.login(data);
reset(); // clears all inputs
}
// Pre-fill with existing profile data:
useEffect(() => {
if (userProfile) {
reset({
name: userProfile.name,
email: userProfile.email,
});
}
}, [userProfile]);Form Validation Modes
react-hook-form offers several mode settings that control when validation runs: 'onSubmit' (default, validates only on submit), 'onBlur' (validates when a field loses focus), 'onChange' (validates on every keystroke), and 'all' (combines onBlur and onChange). For mobile forms, 'onBlur' offers the best balance between immediate feedback and avoiding distracting errors while typing.
const { control, handleSubmit } = useForm<LoginForm>({
mode: 'onBlur', // validate when user leaves a field
defaultValues: { email: '', password: '' },
});Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: useForm creates the form instance with control, handleSubmit, and formState.errors, Controller wires native TextInput components to the form with onChange, onBlur, and value props, and rules define built-in validation constraints that populate errors automatically. Next up we explore validation rules and error message handling in depth.
คำถามที่พบบ่อย
บทเรียน “การตั้งค่า react-hook-form ร่วมกับ Controller” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การตั้งค่า react-hook-form ร่วมกับ Controller” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การตั้งค่า react-hook-form ร่วมกับ Controller”
ติดตั้ง react-hook-form ใช้ useForm เพื่อสร้างอินสแตนซ์ของฟอร์ม และครอบ TextInput แต่ละรายการด้วย Controller เพื่อลงทะเบียนและรับ onChange/onBlur คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การตั้งค่า react-hook-form ร่วมกับ Controller” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตั้งค่า react-hook-form ร่วมกับ Controller
- กฎการตรวจสอบและข้อความแสดงข้อผิดพลาด
- ฟอร์มหลายขั้นตอนพร้อมสถานะฟอร์ม
- การส่งและรีเซ็ตฟอร์ม