Lesson 65 of 60 – TypeScript with Button
100%

TypeScript with Button

The Button component is used to perform actions when a user presses a button in a React Native application. With TypeScript, we can safely type button handler functions, component props, state, and data used by our buttons.

Note: In React Native, the onPress prop is used to execute a function when the Button is pressed. TypeScript helps ensure that the function has the correct type.

1. What is Button?

Button is a built-in React Native component that allows users to perform an action by pressing a button.

import { Button } from "react-native";

<Button
    title="Click Me"
    onPress={() => {
        console.log("Button pressed");
    }}
/>

2. Importing Button

Import Button from React Native before using it.

import { Button } from "react-native";

React Native already provides TypeScript definitions for the Button component.

3. Basic Button Example

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

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

    return (
        <View>
            <Button
                title="Click Me"
                onPress={() => {
                    console.log("Clicked");
                }}
            />
        </View>
    );
}

4. The title Prop

The title prop specifies the text displayed on the Button.

<Button
    title="Login"
    onPress={() => {
        console.log("Login");
    }}
/>

The title is normally provided as a string.

5. The onPress Prop

The onPress prop receives a function that runs when the button is pressed.

const handlePress = (): void => {
    console.log("Button pressed");
};

<Button
    title="Press"
    onPress={handlePress}
/>

6. Typing a Button Handler

A function that does not return a value can be typed with void.

const handlePress = (): void => {
    console.log("Hello");
};

This tells TypeScript that the function does not return a value.

7. Calling a Typed Function

const handlePress = (): void => {
    console.log("Saved");
};

<Button
    title="Save"
    onPress={handlePress}
/>

The Button calls the typed function when it is pressed.

8. Inline onPress Function

The handler can also be written directly inside the Button.

<Button
    title="Submit"
    onPress={() => {
        console.log("Submitted");
    }}
/>

This is useful for short actions.

9. Button with useState

Buttons are often used to change React state.

const [count, setCount] =
    useState<number>(0);

const increase = (): void => {
    setCount(count + 1);
};

<Button
    title="Increase"
    onPress={increase}
/>

10. Displaying Button State

<Text>
    Count: {count}
</Text>

<Button
    title="Increase"
    onPress={increase}
/>

The Button changes the state and the Text displays the updated value.

11. Button with Boolean State

const [loggedIn, setLoggedIn] =
    useState<boolean>(false);

const login = (): void => {
    setLoggedIn(true);
};

<Button
    title="Login"
    onPress={login}
/>

TypeScript ensures that loggedIn is a boolean.

12. Conditional Button Text

Button titles can be changed based on state.

<Button
    title={loggedIn ? "Logout" : "Login"}
    onPress={login}
/>

A conditional expression selects the displayed title.

13. Passing Arguments to a Button Function

A Button can call a function with an argument using an arrow function.

const showUser = (name: string): void => {
    console.log(name);
};

<Button
    title="Show User"
    onPress={() => {
        showUser("Rahul");
    }}
/>

14. Typed Function Parameters

const showAge = (age: number): void => {
    console.log(age);
};

<Button
    title="Show Age"
    onPress={() => {
        showAge(21);
    }}
/>

The age parameter must be a number.

15. Button with String State

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

const showMessage = (): void => {
    setMessage("Welcome to React Native");
};

<Button
    title="Show Message"
    onPress={showMessage}
/>

<Text>{message}</Text>

16. Button with Multiple Actions

A single handler can perform multiple operations.

const saveData = (): void => {

    console.log("Saving data");

    setMessage("Data saved");

    console.log("Operation completed");
};

The function can then be passed to the Button.

17. Disabled Button

The disabled prop can prevent a Button from being pressed.

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

<Button
    title="Submit"
    disabled={loading}
    onPress={() => {
        console.log("Submit");
    }}
/>

When loading is true, the Button is disabled.

18. Button with Loading State

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

const submit = (): void => {

    setLoading(true);

    // perform operation

};

Loading state can be used to prevent repeated submissions.

19. Creating Button Props Interface

When creating a reusable Button component, define its props with an interface.

interface CustomButtonProps {
    title: string;
    onPress: () => void;
}

The interface requires a title and an onPress function.

20. Creating a Reusable Button

function CustomButton({
    title,
    onPress
}: CustomButtonProps): React.JSX.Element {

    return (
        <Button
            title={title}
            onPress={onPress}
        />
    );
}

This component can be reused throughout the application.

21. Using the Reusable Button

const save = (): void => {
    console.log("Saved");
};

<CustomButton
    title="Save"
    onPress={save}
/>

TypeScript checks that the required props are provided correctly.

22. Optional Button Props

Additional Button properties can be made optional.

interface CustomButtonProps {
    title: string;
    onPress: () => void;
    disabled?: boolean;
}

The disabled property is optional.

23. Reusable Button with Disabled Prop

function CustomButton({
    title,
    onPress,
    disabled = false
}: CustomButtonProps): React.JSX.Element {

    return (
        <Button
            title={title}
            onPress={onPress}
            disabled={disabled}
        />
    );
}

24. Button with Form Submission

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

const submitForm = (): void => {

    if (form.name.trim() === "") {
        console.log("Name required");
        return;
    }

    if (form.email.trim() === "") {
        console.log("Email required");
        return;
    }

    console.log(form);
};

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

25. Button with API Function

A Button can call a function that performs an API request.

const loadData = async (): Promise<void> => {

    try {

        const response =
            await fetch("https://example.com/api");

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.log(error);

    }
};

The Button can call loadData.

26. Common TypeScript Mistakes with Button

  • Calling a function immediately instead of passing a function.
  • Forgetting to type function parameters.
  • Using any unnecessarily.
  • Passing incorrect values to custom Button props.
  • Forgetting required props such as title or onPress.
  • Using the wrong state type for Button logic.
// Correct
<Button
    title="Save"
    onPress={save}
/>

// Also correct
<Button
    title="Save"
    onPress={() => save()}
/>

27. Best Practices for Typed Buttons

  • Type event handler functions with void when they return nothing.
  • Use interfaces for reusable Button props.
  • Use boolean state for loading and disabled conditions.
  • Keep Button actions inside named functions when they become complex.
  • Use reusable Button components for consistent application design.
  • Avoid unnecessary use of any.
  • Validate form data before performing important actions.

28. Complete Typed Button Example

import React, { useState } from "react";

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

interface CustomButtonProps {
    title: string;
    onPress: () => void;
    disabled?: boolean;
}

function CustomButton({
    title,
    onPress,
    disabled = false
}: CustomButtonProps): React.JSX.Element {

    return (
        <Button
            title={title}
            onPress={onPress}
            disabled={disabled}
        />
    );
}

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

    const [count, setCount] =
        useState<number>(0);

    const increase = (): void => {
        setCount(count + 1);
    };

    const reset = (): void => {
        setCount(0);
    };

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

            <Text style={styles.title}>
                Count: {count}
            </Text>

            <CustomButton
                title="Increase"
                onPress={increase}
            />

            <View style={styles.space} />

            <CustomButton
                title="Reset"
                onPress={reset}
            />

        </View>
    );
}

const styles = StyleSheet.create({

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

    title: {
        fontSize: 24,
        textAlign: "center",
        marginBottom: 20
    },

    space: {
        height: 10
    }

});

29. Why TypeScript is Useful with Button

TypeScript makes Button-related code easier to maintain by checking function parameters, return types, props, state, and reusable components.

  • Safer Button handlers
  • Typed custom Button props
  • Better editor suggestions
  • Safer state management
  • Easier refactoring
  • Fewer type-related errors

30. Summary

The Button component is used to perform actions in React Native. With TypeScript, we can type Button handler functions, state, custom Button props, form functions, and API-related actions.

You should now understand the title and onPress props, typed event handlers, state-based Buttons, disabled Buttons, reusable Button components, and complete TypeScript Button examples.

📌 Key Points

  • Button is used to perform actions in React Native.
  • The title prop defines the Button text.
  • The onPress prop receives a function.
  • Button handler functions can be typed with (): void.
  • Buttons can update typed React state.
  • Custom Button components can use typed interfaces.
  • Boolean state can control the disabled status.
  • Reusable typed Buttons make applications easier to maintain.

🧠 Quick Quiz

Question: Which prop is used to specify the function that runs when a React Native Button is pressed?