------------------------- | User Registration | |-----------------------| | Name: [___________] | | Email: [___________] | | Password: [_______] | | | | [ Register ] | -------------------------
React Hook Form integration in React Native - Mini App: Build & Ship
import React from 'react'; import { View, Text, TextInput, Button, Alert, StyleSheet } from 'react-native'; import { useForm, Controller } from 'react-hook-form'; export default function UserRegistration() { const { control, handleSubmit, formState: { errors } } = useForm(); const onSubmit = data => { // TODO: Show alert with form data }; return ( <View style={styles.container}> {/* TODO: Add Name input with Controller */} {/* TODO: Add Email input with Controller */} {/* TODO: Add Password input with Controller */} {/* TODO: Add Register button to submit form */} </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, justifyContent: 'center' }, input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 5, borderRadius: 4 }, errorText: { color: 'red', marginBottom: 10 } });
import React from 'react'; import { View, Text, TextInput, Button, Alert, StyleSheet } from 'react-native'; import { useForm, Controller } from 'react-hook-form'; export default function UserRegistration() { const { control, handleSubmit, formState: { errors } } = useForm(); const onSubmit = data => { Alert.alert('Registration Successful', `Name: ${data.name}\nEmail: ${data.email}\nPassword: ${data.password}`); }; return ( <View style={styles.container}> <Text>Name:</Text> <Controller control={control} name="name" rules={{ required: 'Name is required' }} render={({ field: { onChange, onBlur, value } }) => ( <TextInput style={styles.input} onBlur={onBlur} onChangeText={onChange} value={value} placeholder="Enter your name" accessibilityLabel="Name input" /> )} /> {errors.name && <Text style={styles.errorText}>{errors.name.message}</Text>} <Text>Email:</Text> <Controller control={control} name="email" rules={{ required: 'Email is required', pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Email is invalid' } }} render={({ field: { onChange, onBlur, value } }) => ( <TextInput style={styles.input} onBlur={onBlur} onChangeText={onChange} value={value} placeholder="Enter your email" keyboardType="email-address" autoCapitalize="none" accessibilityLabel="Email input" /> )} /> {errors.email && <Text style={styles.errorText}>{errors.email.message}</Text>} <Text>Password:</Text> <Controller control={control} name="password" rules={{ required: 'Password is required', minLength: { value: 6, message: 'Password must be at least 6 characters' } }} render={({ field: { onChange, onBlur, value } }) => ( <TextInput style={styles.input} onBlur={onBlur} onChangeText={onChange} value={value} placeholder="Enter your password" secureTextEntry accessibilityLabel="Password input" /> )} /> {errors.password && <Text style={styles.errorText}>{errors.password.message}</Text>} <Button title="Register" onPress={handleSubmit(onSubmit)} accessibilityLabel="Register button" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, justifyContent: 'center' }, input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 5, borderRadius: 4 }, errorText: { color: 'red', marginBottom: 10 } });
This solution uses React Hook Form's useForm hook to manage the form state and validation easily. Each input field is wrapped with a Controller component that connects the React Native TextInput to the form state.
Validation rules are set for each field: Name and Email are required, Email must match a simple email pattern, and Password is required with a minimum length of 6 characters.
Error messages appear below each input if validation fails, helping the user fix mistakes. When the user taps the Register button, handleSubmit runs validation and calls onSubmit if all inputs are valid.
The onSubmit function shows an alert with the entered data, confirming successful registration.
Accessibility labels are added for screen readers, and the layout uses simple styling for clarity and spacing.
------------------------- | User Registration | |-----------------------| | Name: [John Doe ] | | | | Email: [john@example] | | | | Password: [******] | | | | [ Register ] | -------------------------
Practice
React Hook Form in a React Native app?Solution
Step 1: Understand React Hook Form's role
React Hook Form is designed to simplify handling form data and validation in React Native apps.Step 2: Compare options with React Hook Form's purpose
Styling, data fetching, and navigation are handled by other libraries or React Native features, not React Hook Form.Final Answer:
To manage form state and validation easily -> Option DQuick Check:
To manage form state and validation easily = B [OK]
- Confusing React Hook Form with styling libraries
- Thinking it handles navigation or API calls
- Ignoring its validation features
useForm from React Hook Form in a React Native component?Solution
Step 1: Recall correct import syntax for named exports
React Hook Form exportsuseFormas a named export, so curly braces are needed.Step 2: Verify package name correctness
The official package is 'react-hook-form', not 'react-native-hook-form'.Final Answer:
import { useForm } from 'react-hook-form'; -> Option CQuick Check:
Named import from 'react-hook-form' = A [OK]
- Using default import instead of named import
- Wrong package name 'react-native-hook-form'
- Missing curly braces around useForm
const { control, handleSubmit } = useForm();
return (
<Controller
control={control}
name="email"
rules={{ required: true }}
render={({ field: { onChange, value } }) => (
<TextInput
value={value}
onChangeText={onChange}
/>
)}
/>
);What happens if the user submits the form without entering an email?
Solution
Step 1: Understand the validation rule
Therules={{ required: true }}means the email field must have a value.Step 2: Effect of missing required value on submission
If the email is empty, React Hook Form blocks submission and sets an error for that field.Final Answer:
The form submission is blocked and an error is shown -> Option AQuick Check:
Required rule blocks empty submission = C [OK]
- Assuming form submits with empty values
- Expecting automatic default values
- Thinking app crashes on validation error
const { control, handleSubmit } = useForm();
return (
<Controller
control={control}
name="password"
rules={{ minLength: 6 }}
render={({ onChange, value }) => (
<TextInput
value={value}
onChangeText={onChange}
/>
)}
/>
);Solution
Step 1: Check render prop destructuring
The render function receives an object with afieldproperty, which containsonChangeandvalue. Direct destructuring ofonChangeandvalueis incorrect.Step 2: Verify other props
TheminLengthrule accepts a number,controlis present, andnameis correctly placed.Final Answer:
The render prop destructuring is incorrect; should destructure field object -> Option BQuick Check:
Render prop needs field destructuring = D [OK]
- Destructuring onChange and value directly from render argument
- Using string instead of number for minLength
- Omitting control or name props
username and age. The age must be a number greater than 18. Using React Hook Form, which validation rule correctly enforces this for age?Solution
Step 1: Numeric validation from string input
TextInput provides strings;valueAsNumber: truein rules parses to number for validation.Step 2: Rule for >18
min: 19ensures parsed number >= 19 (>18).Step 3: Eliminate others
A'svalidateon string fails ("100" < "18" lexically). B for strings. D opposite.Final Answer:
rules={{ required: true, min: 19, valueAsNumber: true }} -> Option AQuick Check:
valueAsNumber: true + min: 19 = C [OK]
- validate without Number conversion (string "100" > 18 fails)
- minLength for numbers
- max instead of min
Ready to prove it?
Pass the test and this pattern moves unknown
