Lesson 36 of 60 – Forms in React Native
60%

Forms in React Native

Forms are an important part of mobile applications. They allow users to enter information such as names, email addresses, passwords, phone numbers, messages and other data.

In React Native, forms are commonly created using components such as TextInput, Pressable, Button and Switch. State is used to store the values entered by the user.

Note: A React Native form usually connects input components with state, event handlers and validation logic.

1. What is a Form?

A form is a user interface that collects information from the user.

Examples include:

  • Login forms.
  • Registration forms.
  • Admission forms.
  • Contact forms.
  • Payment forms.
  • Profile forms.
  • Search forms.

2. Why are Forms Important?

Forms allow an application to collect information and perform actions based on that information.

  • Collect user details.
  • Allow users to log in.
  • Create accounts.
  • Submit applications.
  • Update profiles.
  • Send messages.
  • Search for information.

3. TextInput in Forms

The TextInput component is one of the most important components used to collect text from users.

import {
    TextInput
} from 'react-native';

<TextInput
    placeholder="Enter your name"
/>

4. Creating State for Form Input

State is used to store the value entered into a form field.

const [name, setName] =
    useState('');

The state starts with an empty string.

5. Connecting TextInput with State

const [name, setName] =
    useState('');

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Enter your name"
/>

This creates a controlled input. The value displayed by the input is connected to the component state.

6. Creating Multiple Form Fields

A form can contain multiple state variables.

const [name, setName] =
    useState('');

const [email, setEmail] =
    useState('');

const [phone, setPhone] =
    useState('');

Each field can have its own state value.

7. Name Input Field

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Enter your name"
    autoCapitalize="words"
/>

The autoCapitalize property can help users enter names more conveniently.

8. Email Input Field

const [email, setEmail] =
    useState('');

<TextInput
    value={email}
    onChangeText={setEmail}
    placeholder="Enter email"
    keyboardType="email-address"
    autoCapitalize="none"
/>

The email keyboard type provides a more suitable keyboard for email input.

9. Password Input Field

const [password, setPassword] =
    useState('');

<TextInput
    value={password}
    onChangeText={setPassword}
    placeholder="Enter password"
    secureTextEntry
/>

secureTextEntry is commonly used when entering passwords.

10. Phone Number Input

const [phone, setPhone] =
    useState('');

<TextInput
    value={phone}
    onChangeText={setPhone}
    placeholder="Enter phone number"
    keyboardType="phone-pad"
/>

A suitable keyboard type can make entering phone numbers easier.

11. Numeric Input

const [age, setAge] =
    useState('');

<TextInput
    value={age}
    onChangeText={setAge}
    placeholder="Enter age"
    keyboardType="numeric"
/>

The keyboardType property can be used to provide an appropriate keyboard for numeric input.

12. Multiline Text Field

Use multiline when users need to enter longer text.

const [message, setMessage] =
    useState('');

<TextInput
    value={message}
    onChangeText={setMessage}
    placeholder="Enter your message"
    multiline
    numberOfLines={5}
/>

13. Form Button

A button can be used to submit the form.

<Button
    title="Submit"
    onPress={handleSubmit}
/>

The handleSubmit function contains the form submission logic.

14. Creating a Submit Handler

const handleSubmit = () => {

    console.log(name);
    console.log(email);
    console.log(phone);

};

The submit handler can collect the current values stored in state.

15. Basic Form Validation

Validation checks whether the entered information meets the required conditions.

const handleSubmit = () => {

    if (name.trim() === '') {

        console.log(
            'Name is required'
        );

        return;

    }

    console.log(
        'Form submitted'
    );

};

16. Validating Email

const handleSubmit = () => {

    if (email.trim() === '') {

        console.log(
            'Email is required'
        );

        return;

    }

};

For a production application, email validation can be made more specific depending on the application's requirements.

17. Validating Password

if (password.length < 6) {

    console.log(
        'Password must contain at least 6 characters'
    );

    return;

}

Validation rules should be chosen according to the requirements of the application.

18. Showing Validation Messages

const [error, setError] =
    useState('');

const handleSubmit = () => {

    if (name.trim() === '') {

        setError(
            'Name is required'
        );

        return;

    }

    setError('');

};

The error state can be displayed below the form field.

19. Displaying an Error Message

{error !== '' && (

    <Text
        style={{
            color: 'red'
        }}
    >
        {error}
    </Text>

)}

The error message appears only when an error exists.

20. Clearing a Form

After successful submission, the form fields can be cleared by resetting their state.

setName('');
setEmail('');
setPhone('');
setMessage('');

21. Form with Loading State

A loading state can be used while a form submission is being processed.

const [loading, setLoading] =
    useState(false);

const handleSubmit = () => {

    setLoading(true);

    // Perform operation

};

The loading state can control a spinner or disable the submit button.

22. Disabling Submit Button

<Button
    title={
        loading
            ? 'Submitting...'
            : 'Submit'
    }
    disabled={loading}
    onPress={handleSubmit}
/>

This can help prevent repeated submissions while an operation is running.

23. Form with Pressable

<Pressable
    style={styles.button}
    onPress={handleSubmit}
>

    <Text
        style={styles.buttonText}
    >
        Submit Form
    </Text>

</Pressable>

Pressable can be used when you need more control over the appearance and touch behavior of a form button.

24. Login Form

const [email, setEmail] =
    useState('');

const [password, setPassword] =
    useState('');

const handleLogin = () => {

    if (
        email.trim() === '' ||
        password.trim() === ''
    ) {

        console.log(
            'All fields are required'
        );

        return;

    }

    console.log(
        'Login submitted'
    );

};

The same form concepts can be used to create registration, admission, contact and profile forms.

25. Form Layout with ScrollView

Long forms may need to be placed inside a ScrollView so users can reach all fields on smaller screens.

<ScrollView
    contentContainerStyle={{
        padding: 20
    }}
>

    <TextInput
        placeholder="Name"
    />

    <TextInput
        placeholder="Email"
    />

    <TextInput
        placeholder="Phone"
    />

    <TextInput
        placeholder="Address"
        multiline
    />

</ScrollView>

26. Common Form Mistakes

  • Not connecting TextInput with state.
  • Forgetting onChangeText.
  • Not validating required fields.
  • Allowing empty values when they are not allowed.
  • Using inappropriate keyboard types.
  • Not displaying useful validation messages.
  • Allowing multiple submissions.
  • Creating unnecessarily complicated form state.
  • Not making long forms scrollable.
  • Not clearing or resetting fields when required.

27. Complete Registration Form Example

import React, {
    useState
} from 'react';

import {
    View,
    Text,
    TextInput,
    Pressable,
    ScrollView,
    StyleSheet
} from 'react-native';

export default function App() {

    const [name, setName] =
        useState('');

    const [email, setEmail] =
        useState('');

    const [password, setPassword] =
        useState('');

    const [error, setError] =
        useState('');

    const [message, setMessage] =
        useState('');

    const handleSubmit = () => {

        setError('');
        setMessage('');

        if (name.trim() === '') {

            setError(
                'Name is required'
            );

            return;

        }

        if (email.trim() === '') {

            setError(
                'Email is required'
            );

            return;

        }

        if (password.length < 6) {

            setError(
                'Password must contain at least 6 characters'
            );

            return;

        }

        setMessage(
            'Registration successful!'
        );

        setName('');
        setEmail('');
        setPassword('');

    };

    return (

        <ScrollView
            contentContainerStyle={
                styles.container
            }
        >

            <Text style={styles.title}>
                Registration Form
            </Text>

            <TextInput
                style={styles.input}
                value={name}
                onChangeText={setName}
                placeholder="Enter your name"
                autoCapitalize="words"
            />

            <TextInput
                style={styles.input}
                value={email}
                onChangeText={setEmail}
                placeholder="Enter your email"
                keyboardType="email-address"
                autoCapitalize="none"
            />

            <TextInput
                style={styles.input}
                value={password}
                onChangeText={setPassword}
                placeholder="Enter password"
                secureTextEntry
            />

            {error !== '' && (

                <Text
                    style={styles.error}
                >
                    {error}
                </Text>

            )}

            {message !== '' && (

                <Text
                    style={styles.success}
                >
                    {message}
                </Text>

            )}

            <Pressable
                style={styles.button}
                onPress={handleSubmit}
            >

                <Text
                    style={styles.buttonText}
                >
                    Register
                </Text>

            </Pressable>

        </ScrollView>

    );

}

const styles = StyleSheet.create({

    container: {
        padding: 20,
        flexGrow: 1,
        justifyContent: 'center'
    },

    title: {
        fontSize: 28,
        fontWeight: 'bold',
        marginBottom: 20
    },

    input: {
        borderWidth: 1,
        borderColor: '#CBD5E1',
        borderRadius: 8,
        padding: 12,
        marginBottom: 12
    },

    button: {
        marginTop: 15,
        padding: 14,
        borderRadius: 8,
        backgroundColor: '#2563EB',
        alignItems: 'center'
    },

    buttonText: {
        color: 'white',
        fontWeight: 'bold'
    },

    error: {
        color: 'red',
        marginTop: 5
    },

    success: {
        color: 'green',
        marginTop: 5
    }

});

28. Form Best Practices

  • Use controlled inputs for form values.
  • Use meaningful state names.
  • Validate important fields.
  • Show clear validation messages.
  • Use suitable keyboard types.
  • Use secure text entry for passwords.
  • Disable submission while an operation is running when appropriate.
  • Use ScrollView for long forms.
  • Keep form logic organized.
  • Clear sensitive information carefully when appropriate.

29. Common Form Components

Component / Feature Purpose
TextInput Enter text and other input values
Button Perform a simple form action
Pressable Create customizable interactive buttons
Switch Select a true/false option
ScrollView Make long forms scrollable
useState Store form values and UI state
onChangeText Respond to text changes
onPress Respond to button presses

30. Complete Form Development Workflow

Plan Form Fields
        ↓
Create Form UI
        ↓
Create State Variables
        ↓
Connect TextInput with State
        ↓
Add Submit Button
        ↓
Create Submit Handler
        ↓
Validate Input
        ↓
Show Validation Messages
        ↓
Process Form Data
        ↓
Show Success or Error Result
        ↓
Reset Form When Required

Forms combine several important React Native concepts such as TextInput, state, events, validation and reusable components. Understanding forms is essential for building real-world mobile applications.

📌 Key Points

  • Forms are used to collect information from users.
  • TextInput is commonly used for entering data.
  • useState is used to store form values.
  • onChangeText updates input state.
  • Buttons and Pressable can submit forms.
  • Validation checks whether the entered data is acceptable.
  • Error messages help users correct invalid input.
  • ScrollView is useful for long forms.
  • Loading state can prevent repeated submissions.
  • Forms are essential for login, registration, admission, contact and profile screens.

🧠 Quick Quiz

Question: Which React Native component is commonly used to accept text input from the user?