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.
onPress prop is used to execute a
function when the Button is pressed. TypeScript helps ensure that the
function has the correct type.
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");
}}
/>
Import Button from React Native before using it.
import { Button } from "react-native";
React Native already provides TypeScript definitions for the Button component.
import {
View,
Button
} from "react-native";
export default function App(): React.JSX.Element {
return (
<View>
<Button
title="Click Me"
onPress={() => {
console.log("Clicked");
}}
/>
</View>
);
}
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.
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}
/>
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.
const handlePress = (): void => {
console.log("Saved");
};
<Button
title="Save"
onPress={handlePress}
/>
The Button calls the typed function when it is pressed.
The handler can also be written directly inside the Button.
<Button
title="Submit"
onPress={() => {
console.log("Submitted");
}}
/>
This is useful for short actions.
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}
/>
<Text>
Count: {count}
</Text>
<Button
title="Increase"
onPress={increase}
/>
The Button changes the state and the Text displays the updated value.
const [loggedIn, setLoggedIn] =
useState<boolean>(false);
const login = (): void => {
setLoggedIn(true);
};
<Button
title="Login"
onPress={login}
/>
TypeScript ensures that loggedIn is a boolean.
Button titles can be changed based on state.
<Button
title={loggedIn ? "Logout" : "Login"}
onPress={login}
/>
A conditional expression selects the displayed title.
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");
}}
/>
const showAge = (age: number): void => {
console.log(age);
};
<Button
title="Show Age"
onPress={() => {
showAge(21);
}}
/>
The age parameter must be a number.
const [message, setMessage] =
useState<string>("");
const showMessage = (): void => {
setMessage("Welcome to React Native");
};
<Button
title="Show Message"
onPress={showMessage}
/>
<Text>{message}</Text>
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.
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.
const [loading, setLoading] =
useState<boolean>(false);
const submit = (): void => {
setLoading(true);
// perform operation
};
Loading state can be used to prevent repeated submissions.
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.
function CustomButton({
title,
onPress
}: CustomButtonProps): React.JSX.Element {
return (
<Button
title={title}
onPress={onPress}
/>
);
}
This component can be reused throughout the application.
const save = (): void => {
console.log("Saved");
};
<CustomButton
title="Save"
onPress={save}
/>
TypeScript checks that the required props are provided correctly.
Additional Button properties can be made optional.
interface CustomButtonProps {
title: string;
onPress: () => void;
disabled?: boolean;
}
The disabled property is optional.
function CustomButton({
title,
onPress,
disabled = false
}: CustomButtonProps): React.JSX.Element {
return (
<Button
title={title}
onPress={onPress}
disabled={disabled}
/>
);
}
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}
/>
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.
any unnecessarily.// Correct
<Button
title="Save"
onPress={save}
/>
// Also correct
<Button
title="Save"
onPress={() => save()}
/>
void when they return nothing.any.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
}
});
TypeScript makes Button-related code easier to maintain by checking function parameters, return types, props, state, and reusable components.
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.
Button is used to perform actions in React Native.title prop defines the Button text.onPress prop receives a function.(): void.Question: Which prop is used to specify the function that runs when a React Native Button is pressed?