0
0
React Nativemobile~20 mins

React Hook Form integration in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: User Registration
A simple user registration form using React Hook Form to handle input validation and submission.
Target UI
-------------------------
| User Registration     |
|-----------------------|
| Name: [___________]   |
| Email: [___________]  |
| Password: [_______]   |
|                       |
| [ Register ]          |
-------------------------
Use React Hook Form to manage form state and validation.
Include three input fields: Name, Email, and Password.
Validate that Name and Email are required.
Validate that Email has a proper email format.
Validate that Password is required and at least 6 characters.
Show error messages below each input if validation fails.
On successful submission, display an alert with the entered data.
Starter Code
React Native
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
  }
});
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
React Native
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.

Final Result
Completed Screen
-------------------------
| User Registration     |
|-----------------------|
| Name: [John Doe    ]  |
|                       |
| Email: [john@example] |
|                       |
| Password: [******]    |
|                       |
| [ Register ]          |
-------------------------
User types in Name, Email, and Password fields.
If a field is empty or invalid, an error message appears below it.
Tapping Register validates inputs.
If valid, an alert pops up showing the entered Name, Email, and Password.
If invalid, errors remain visible until fixed.
Stretch Goal
Add a toggle button to show or hide the password input text.
💡 Hint
Use a state variable to switch the TextInput's secureTextEntry prop between true and false.