← Back to Chapters

React Native Alert API

? React Native Alert API

? Quick Overview

The Alert API in React Native is used to show native alert dialogs to users. It is commonly used for confirmations, warnings, errors, and important messages. Alerts are platform-native, meaning they look and feel like real system dialogs on Android and iOS.

? Key Concepts

  • Alerts are modal and block user interaction until dismissed
  • Supports title, message, and buttons
  • Buttons can have callbacks for user actions
  • Uses native UI components under the hood

? Syntax / Theory

The Alert API is available from the react-native package. The most commonly used method is Alert.alert().

Basic syntax:

? View Code Example
// Import Alert from react-native
import { Alert } from 'react-native';

// Show a basic alert dialog
Alert.alert(
  'Title',
  'Alert message goes here'
);

? Code Example(s)

Example showing multiple buttons with different actions.

? View Code Example
// Alert with multiple action buttons
Alert.alert(
  'Delete Item',
  'Are you sure you want to delete this item?',
  [
    {
      text: 'Cancel',
      onPress: () => console.log('Cancel pressed'),
      style: 'cancel',
    },
    {
      text: 'Delete',
      onPress: () => console.log('Delete pressed'),
      style: 'destructive',
    },
  ]
);

⚡ Interactive Simulator

Since React Native runs on mobile devices, this simulator mimics how the Alert API works using Web technologies. Click the buttons to trigger the alerts.

// Console logs will appear here...
Title
Message
 

? Live Output / Explanation

What Happens?

  • A system alert dialog appears on the screen
  • User must tap one of the buttons
  • The corresponding callback function is executed
  • The alert closes automatically after selection

? Interactive / Visual Understanding

Conceptual flow of how Alert API works:

User Action Alert Dialog Callback

? Use Cases

  • Delete confirmation dialogs
  • Form submission success or error messages
  • Logout confirmation
  • Critical warnings or system messages

? Tips & Best Practices

  • Keep alert messages short and clear
  • Use destructive style for dangerous actions
  • Avoid overusing alerts as they interrupt user flow
  • Prefer custom modals for complex UI needs

? Try It Yourself

  1. Create a button in React Native
  2. Trigger Alert.alert() on button press
  3. Add at least two buttons with callbacks
  4. Log different messages for each action