In React Native, the Button component is used to trigger actions when a user taps on it. The onPress prop defines the function that runs when the button is pressed.
The onPress event accepts a function. This function executes when the user taps the button.
// Import required components from react-native
import React from "react";
import { View, Button, Alert } from "react-native";
const App = () => {
// Function executed when button is pressed
const handlePress = () => {
Alert.alert("Button Pressed", "You clicked the button!");
};
return (
<View>
<Button title="Click Me" onPress={handlePress} />
</View>
);
};
export default App;
When the user taps the Click Me button, the handlePress function runs and shows an alert message on the screen.
Test the onPress logic below. Clicking the button will update the state, simulating a real React Native interaction.
const [count, setCount] = useState(0);
// This function runs when you tap the button
<Button
title="PRESS ME"
onPress={() => setCount(count + 1)}
/>