Lesson 63 of 60 – TypeScript with Text
100%

TypeScript with Text

The Text component is used to display text content in React Native applications. When using TypeScript, we can safely type the data displayed inside Text components and the props of our custom text components.

Note: React Native provides built-in TypeScript definitions for Text. TypeScript becomes especially useful when we create reusable components and pass typed data to them.

1. What is Text?

Text is a React Native component used to display text on the screen.

import { Text } from "react-native";

<Text>Hello React Native</Text>

Text is commonly used for headings, labels, messages, names, and other textual information.

2. Importing Text

Import Text from React Native before using it.

import { Text } from "react-native";

React Native already provides TypeScript support for the Text component.

3. Basic Text Example

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

export default function App(): React.JSX.Element {
    return (
        <View>
            <Text>Welcome to React Native</Text>
        </View>
    );
}

The Text component displays the message inside the View.

4. Displaying a String

A string can be displayed directly inside Text.

const name: string = "Rahul";

<Text>{name}</Text>

The variable is explicitly typed as a string.

5. Text with Number Data

Numeric data can also be displayed using Text.

const age: number = 21;

<Text>Age: {age}</Text>

TypeScript ensures that age is a number.

6. Text with Boolean Data

Boolean values can be used to conditionally display text.

const isActive: boolean = true;

{isActive && (
    <Text>Student is Active</Text>
)}

7. Styling Text

The Text component supports styling through the style prop.

<Text style={{ fontSize: 20 }}>
    Hello
</Text>

Text styles can control size, weight, alignment, and color.

8. Using StyleSheet with Text

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

const styles = StyleSheet.create({
    title: {
        fontSize: 24,
        fontWeight: "bold"
    }
});

The style can then be applied to Text.

9. Applying a Text Style

<Text style={styles.title}>
    Student Profile
</Text>

Keeping styles in StyleSheet makes the code easier to organize.

10. Creating a Typed Text Component

We can create our own reusable Text component with TypeScript props.

interface TitleProps {
    title: string;
}

function Title({
    title
}: TitleProps): React.JSX.Element {

    return (
        <Text>{title}</Text>
    );
}

11. Using a Typed Text Component

<Title title="Student Details" />

Because title is typed as a string, TypeScript can check the value passed to the component.

12. Optional Text Props

A custom Text component can also have optional properties.

interface LabelProps {
    text?: string;
}

The question mark makes the property optional.

13. Text with Children

A reusable Text component can accept children.

interface LabelProps {
    children: React.ReactNode;
}

function Label({
    children
}: LabelProps): React.JSX.Element {

    return (
        <Text>{children}</Text>
    );
}

14. Using Text Children

<Label>
    Student Name
</Label>

The content between the opening and closing tags is passed through the children prop.

15. Text with Interface Data

interface Student {
    name: string;
    course: string;
}

const student: Student = {
    name: "Rahul",
    course: "React Native"
};

<Text>
    {student.name}
</Text>

Interfaces help define the structure of application data.

16. Displaying Multiple Values

interface Student {
    name: string;
    age: number;
    course: string;
}

const student: Student = {
    name: "Rahul",
    age: 21,
    course: "React Native"
};

<Text>
    {student.name} - {student.course}
</Text>

17. Conditional Text

TypeScript variables can be used with conditional rendering.

const isLoggedIn: boolean = true;

<Text>
    {isLoggedIn ? "Welcome User" : "Please Login"}
</Text>

18. Union Types with Text

Union types allow a variable to have more than one permitted type.

let value: string | number;

value = "Student";
value = 101;

<Text>{String(value)}</Text>

TypeScript allows both string and number values for value.

19. Text with useState

Text is frequently used to display React state.

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

<Text>
    Hello {name}
</Text>

The state is explicitly typed as a string.

20. Nullable Text State

Sometimes text data may initially be null.

const [message, setMessage] =
    useState<string | null>(null);

{message && (
    <Text>{message}</Text>
)}

The union type tells TypeScript that the state can contain a string or null.

21. Text with Array Data

const names: string[] = [
    "Rahul",
    "Amit",
    "Priya"
];

{names.map((name: string) => (
    <Text key={name}>
        {name}
    </Text>
))}

The array is explicitly defined as an array of strings.

22. Text with Object Array

interface Student {
    id: number;
    name: string;
}

const students: Student[] = [
    { id: 1, name: "Rahul" },
    { id: 2, name: "Priya" }
];

{students.map((student: Student) => (
    <Text key={student.id}>
        {student.name}
    </Text>
))}

23. Reusable Text Component with Style

interface HeadingProps {
    text: string;
}

function Heading({
    text
}: HeadingProps): React.JSX.Element {

    return (
        <Text style={styles.heading}>
            {text}
        </Text>
    );
}

A custom component can combine typed props and reusable styles.

24. Creating Different Text Types

We can create reusable components for headings, labels, and messages.

function Heading({
    text
}: { text: string }): React.JSX.Element {

    return (
        <Text style={styles.heading}>
            {text}
        </Text>
    );
}

function Label({
    text
}: { text: string }): React.JSX.Element {

    return (
        <Text style={styles.label}>
            {text}
        </Text>
    );
}

25. Common TypeScript Mistakes with Text

  • Passing a number to a prop typed as string.
  • Forgetting to type custom component props.
  • Using undefined data without checking it.
  • Using any unnecessarily.
  • Forgetting that nullable values need proper handling.

26. Text and Undefined Data

When data may be undefined, check it before displaying it.

interface User {
    name?: string;
}

const user: User = {};

{user.name ? (
    <Text>{user.name}</Text>
) : (
    <Text>Name not available</Text>
)}

27. Best Practices for Typed Text

  • Use interfaces for complex data structures.
  • Use string types for text-based props.
  • Use reusable Text components.
  • Keep styles organized with StyleSheet.
  • Handle nullable and optional data safely.
  • Avoid unnecessary use of any.

28. Complete Typed Text Example

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

interface StudentProps {
    name: string;
    course: string;
    age: number;
}

function StudentInfo({
    name,
    course,
    age
}: StudentProps): React.JSX.Element {

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

            <Text style={styles.heading}>
                Student Details
            </Text>

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

            <Text>
                Age: {age}
            </Text>

            <Text>
                Course: {course}
            </Text>

        </View>
    );
}

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

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

            <StudentInfo
                name="Rahul"
                age={21}
                course="React Native"
            />

        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 20
    },

    card: {
        padding: 20,
        borderWidth: 1,
        borderRadius: 10
    },

    heading: {
        fontSize: 22,
        fontWeight: "bold",
        marginBottom: 10
    }
});

29. Why TypeScript is Useful with Text

TypeScript makes text-based components safer and easier to maintain. It helps us check props, state, arrays, objects, and application data before running the application.

  • Safer component props
  • Better code completion
  • Better data checking
  • Easier refactoring
  • Fewer type-related errors

30. Summary

The Text component is used to display text in React Native. With TypeScript, we can strongly type the data and props used by Text and reusable text components.

You should now understand how to use strings, numbers, objects, arrays, state, interfaces, children, and reusable components with typed Text.

📌 Key Points

  • Text is used to display text in React Native.
  • Strings and numbers can be safely displayed using typed variables.
  • Custom Text components can have typed props.
  • Interfaces are useful for complex Text component data.
  • React.ReactNode can be used for children.
  • Text can display data from state, arrays, and objects.
  • Optional and nullable data should be handled safely.
  • Reusable Text components make applications easier to maintain.

🧠 Quick Quiz

Question: Which React Native component is used to display text?