← Back to Chapters

React Native Button & onPress

? React Native Button & onPress

? Quick Overview

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.

? Key Concepts

  • Button is a core React Native component
  • onPress handles user interaction
  • Functions can be inline or separate
  • Used for navigation, alerts, API calls, and state updates

? Syntax / Theory

The onPress event accepts a function. This function executes when the user taps the button.

? Code Example

? View Code Example
// 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;

? Live Output / Explanation

What Happens?

When the user taps the Click Me button, the handlePress function runs and shows an alert message on the screen.

? Interactive Example

Test the onPress logic below. Clicking the button will update the state, simulating a real React Native interaction.

Count: 0
? View Logic Used Above
const [count, setCount] = useState(0);

// This function runs when you tap the button
<Button
  title="PRESS ME"
  onPress={() => setCount(count + 1)} 
/>

? Use Cases

  • Submitting forms
  • Navigating between screens
  • Showing alerts or modals
  • Triggering API requests

? Tips & Best Practices

  • Keep onPress functions lightweight
  • Avoid heavy logic directly inside onPress
  • Use custom buttons for advanced styling
  • Always provide clear button labels

? Try It Yourself

  • Create a button that changes text when pressed
  • Trigger a counter increment using onPress
  • Show a confirmation alert before an action