Lesson 64 of 60 – TypeScript with TextInput
100%

TypeScript with TextInput

The TextInput component is used to accept text input from users in React Native applications. With TypeScript, we can safely type the input state, event handlers, component props, and form data.

Note: In React Native, TextInput commonly uses onChangeText to receive the entered text. TypeScript helps ensure that the value handled by our code has the expected type.

1. What is TextInput?

TextInput is a React Native component that allows users to enter text.

import { TextInput } from "react-native";

<TextInput />

It is commonly used for login forms, registration forms, search boxes, feedback forms, and other user input fields.

2. Importing TextInput

Import TextInput from React Native before using it.

import { TextInput } from "react-native";

React Native provides TypeScript definitions for the TextInput component.

3. Basic TextInput Example

import {
    View,
    TextInput
} from "react-native";

export default function App(): React.JSX.Element {

    return (
        <View>
            <TextInput />
        </View>
    );
}

This creates a basic input field.

4. Adding a Placeholder

The placeholder prop displays helpful text when the input is empty.

<TextInput
    placeholder="Enter your name"
/>

The placeholder helps users understand what information they should enter.

5. Creating String State

TextInput values are commonly stored in React state.

const [name, setName] =
    useState<string>("");

The state is explicitly typed as a string.

6. Using value with TextInput

The value prop can connect TextInput to state.

const [name, setName] =
    useState<string>("");

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

This creates a controlled input.

7. Using onChangeText

The onChangeText prop is used to receive the updated text.

<TextInput
    value={name}
    onChangeText={(text: string) => {
        setName(text);
    }}
/>

The text parameter is typed as a string.

8. Complete Controlled TextInput

const [name, setName] =
    useState<string>("");

<TextInput
    value={name}
    placeholder="Enter your name"
    onChangeText={(text: string) => {
        setName(text);
    }}
/>

This is a common pattern for handling text input with TypeScript.

9. Displaying Entered Text

<TextInput
    value={name}
    onChangeText={(text: string) => {
        setName(text);
    }}
/>

<Text>
    Your Name: {name}
</Text>

The value entered by the user can be displayed using a Text component.

10. Styling TextInput

TextInput can be styled using the style prop.

<TextInput
    style={{
        borderWidth: 1,
        padding: 10
    }}
    placeholder="Enter name"
/>

11. Using StyleSheet

const styles = StyleSheet.create({
    input: {
        borderWidth: 1,
        borderRadius: 8,
        padding: 10,
        marginBottom: 10
    }
});

A StyleSheet keeps input styles organized and reusable.

12. Applying Input Style

<TextInput
    style={styles.input}
    placeholder="Enter your name"
/>

The same style can be reused for multiple input fields.

13. Secure Password Input

Password fields can hide the entered characters using secureTextEntry.

<TextInput
    placeholder="Enter password"
    secureTextEntry
/>

This is commonly used for login and registration screens.

14. Email Input

The keyboardType prop can provide an appropriate keyboard for specific input.

<TextInput
    placeholder="Enter email"
    keyboardType="email-address"
/>

This is useful when collecting email addresses.

15. Number Input

const [age, setAge] =
    useState<string>("");

<TextInput
    value={age}
    placeholder="Enter age"
    keyboardType="numeric"
    onChangeText={(text: string) => {
        setAge(text);
    }}
/>

TextInput values are received as text, even when a numeric keyboard is used.

16. Converting Text to Number

If the application needs a number, the string can be converted.

const numberValue: number =
    Number(age);

This keeps the TextInput state as a string while converting the value when numeric processing is required.

17. Multiple TextInputs

A form can contain multiple TextInput components with separate state.

const [name, setName] =
    useState<string>("");

const [email, setEmail] =
    useState<string>("");

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

<TextInput
    value={email}
    onChangeText={setEmail}
    placeholder="Email"
/>

18. Creating a Form Interface

An interface can describe the structure of form data.

interface FormData {
    name: string;
    email: string;
    phone: string;
}

This is useful when a form contains several related fields.

19. Using Typed Form State

const [form, setForm] =
    useState<FormData>({
        name: "",
        email: "",
        phone: ""
    });

TypeScript now knows the structure of the form state.

20. Updating Form State

setForm({
    ...form,
    name: text
});

The spread operator keeps the existing form values while updating one field.

Because form is typed as FormData, TypeScript can check the object structure.

21. Reusable Input Component

We can create a reusable TextInput component with typed props.

interface InputProps {
    value: string;
    placeholder: string;
    onChangeText: (text: string) => void;
}

The function type ensures that the callback receives a string.

22. Creating the Typed Input Component

function Input({
    value,
    placeholder,
    onChangeText
}: InputProps): React.JSX.Element {

    return (
        <TextInput
            value={value}
            placeholder={placeholder}
            onChangeText={onChangeText}
            style={styles.input}
        />
    );
}

23. Using the Reusable Input

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

The reusable component keeps the input code consistent throughout the application.

24. Input Validation

TypeScript does not replace validation. We still need to check whether the entered data is valid.

if (name.trim() === "") {
    setError("Name is required");
}

TypeScript checks types, while application logic checks the actual values.

25. Showing Validation Errors

const [error, setError] =
    useState<string>("");

{error !== "" && (
    <Text style={styles.error}>
        {error}
    </Text>
)}

The error message can be displayed below the input field.

26. Clearing TextInput

The input can be cleared by changing its state to an empty string.

const clearInput = (): void => {
    setName("");
};

A Button or Pressable component can call this function.

27. Common TypeScript Mistakes with TextInput

  • Using a number state directly for TextInput text.
  • Forgetting that onChangeText receives a string.
  • Using any instead of proper types.
  • Forgetting to type reusable component props.
  • Not handling optional or nullable form data.
  • Changing form state without preserving other fields.

28. Complete Typed TextInput Form

import React, { useState } from "react";

import {
    View,
    Text,
    TextInput,
    Button,
    StyleSheet
} from "react-native";

interface FormData {
    name: string;
    email: string;
}

export default function App(): React.JSX.Element {

    const [form, setForm] =
        useState<FormData>({
            name: "",
            email: ""
        });

    const [error, setError] =
        useState<string>("");

    const submitForm = (): void => {

        if (form.name.trim() === "") {
            setError("Name is required");
            return;
        }

        if (form.email.trim() === "") {
            setError("Email is required");
            return;
        }

        setError("");
        console.log(form);
    };

    return (
        <View style={styles.container}>

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

            <TextInput
                style={styles.input}
                placeholder="Enter name"
                value={form.name}
                onChangeText={(text: string) =>
                    setForm({
                        ...form,
                        name: text
                    })
                }
            />

            <TextInput
                style={styles.input}
                placeholder="Enter email"
                keyboardType="email-address"
                value={form.email}
                onChangeText={(text: string) =>
                    setForm({
                        ...form,
                        email: text
                    })
                }
            />

            {error !== "" && (
                <Text style={styles.error}>
                    {error}
                </Text>
            )}

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

        </View>
    );
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        padding: 20,
        justifyContent: "center"
    },

    heading: {
        fontSize: 24,
        fontWeight: "bold",
        marginBottom: 20
    },

    input: {
        borderWidth: 1,
        borderRadius: 8,
        padding: 10,
        marginBottom: 12
    },

    error: {
        marginBottom: 10
    }

});

29. Best Practices for Typed TextInput

  • Use useState<string> for simple text fields.
  • Use interfaces for larger forms.
  • Use onChangeText for handling input text.
  • Type callback functions correctly.
  • Keep reusable input components strongly typed.
  • Validate form values before submitting.
  • Keep styles organized with StyleSheet.
  • Avoid unnecessary use of any.

30. Summary

The TextInput component is essential for accepting user input in React Native applications. TypeScript makes TextInput-based forms safer by providing types for state, callbacks, props, and form objects.

You should now understand controlled TextInputs, typed string state, input styling, password and numeric inputs, reusable input components, form interfaces, validation, and complete typed forms.

📌 Key Points

  • TextInput is used to accept user input.
  • TextInput values are commonly stored as string state.
  • onChangeText receives the entered text as a string.
  • Controlled inputs use value and onChangeText.
  • Interfaces are useful for forms with multiple fields.
  • Reusable TextInput components can have typed props.
  • Validation should be performed before submitting form data.
  • TypeScript helps prevent incorrect data types in forms.

🧠 Quick Quiz

Question: Which TextInput prop is commonly used to receive changed text in React Native?