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.
The Alert API is available from the react-native package. The most commonly used method is Alert.alert().
Basic syntax:
// Import Alert from react-native
import { Alert } from 'react-native';
// Show a basic alert dialog
Alert.alert(
'Title',
'Alert message goes here'
);
Example showing multiple buttons with different actions.
// 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',
},
]
);
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.
Conceptual flow of how Alert API works:
Alert.alert() on button press