React Native
Form libraries
Learn form libraries like react-hook-form.
react-hook-form
react-hook-form is a popular library for managing forms. Instead of writing useState and onChangeText by hand, you build the form with the useForm hook. This library is performant; it prevents the whole component from re-rendering on every keystroke.
Basic usage: const { register, handleSubmit, errors } = useForm();. register registers a field with the form system. handleSubmit runs validation and, on success, hands the data to your handler. errors carries the validation errors. In React Native it is common to use the Controller component instead of register; this is because TextInput is not a standard HTML input. Beyond uniform form management this library lets you write validation rules in a declarative way.
Exercise Write a form with useForm
Write a SimpleForm component. Import useForm from react-hook-form. Call const { register, handleSubmit } = useForm();. The onSubmit function calls console.log(data). Return an input and a Button; bind the button with onPress={handleSubmit(onSubmit)}.
Show example solution
import { useForm } from "react-hook-form";
import { Button, TextInput } from "react-native";
function SimpleForm() {
const { register, handleSubmit } = useForm();
function onSubmit(data) {
console.log(data);
}
return (
<>
<TextInput placeholder="Name" {...register("name")} />
<Button onPress={handleSubmit(onSubmit)} title="Submit" />
</>
);
}
Controller with TextInput
In React Native TextInput is not a standard HTML input so register does not work directly. Instead you use the Controller component. Controller wraps the field and reports changes to the form system.
Example: <Controller control={control} name="email" defaultValue="" render={({ field: { onChange, value } }) => (<TextInput value={value} onChangeText={onChange} />)} />. Here control comes from useForm; name is the field name; render draws the actual input. Through field.onChange every change reaches the form system. This approach makes custom inputs like TextInput work with react-hook-form. Validation rules are also written on the Controller as rules={{ required: true }}.
Test yourself
-
Take handleSubmit from useForm
const { ____ } = useForm();
Show answer
const { handleSubmit } = useForm();
-
Match the concept to its role
- useForm
- Form hook
- handleSubmit
- Validate and submit
- Controller
- Wraps TextInput
- register
- Registers a field
-
Why prefer react-hook-form?
const { handleSubmit } = useForm();
- Re-renders the whole component on every keystroke
- Manages validation and submission declaratively
- It is only for the web
- It doesn't replace useState
Show answer
Manages validation and submission declaratively — react-hook-form manages validation and submission declaratively.
Next lesson: Summary - Form handling