What is the Alert?
In React Native, Alert
is used to show important information or just prompt the user for confirmation. You can use the Alert.alert()
method anywhere in your app to display an alert or Alert.prompt()
to request an input from user.
Buttons in Alert
To include action buttons in the Alert, simply pass them as a third parameter in Alert.alert()
. Each button can have its own onPress
event handler.
import { Alert } from 'react-native';
Alert.alert(
'Confirmation',
'Do you want to proceed?',
[
{ text: 'Cancel', onPress: () => console.log('Cancel Pressed'), },
{ text: 'OK', onPress: () => console.log('OK Pressed') },
],
);
Style
Due to Alert being a Core Component, there's not much style-wise you can change. You can, however, set the style of action buttons to either default
, cancel
, or destructive
to distinguish them.
Unfortunately, this option is only available on iOS devices.
import { Alert } from 'react-native';
Alert.alert('Confirmation', 'Do you want to proceed?', [
{
style: 'default',
text: 'OK',
onPress: () => {},
},
{
style: 'destructive',
text: 'Delete',
onPress: () => {},
},
{
style: 'cancel',
text: 'Cancel',
onPress: () => {},
},
]);
Confirmation Alert
One of the useful use cases is to wrap the Alert
in a promise and then just use it as a one-line confirmation popup.
export const confirm = message =>
new Promise(resolve =>
Alert.alert('Confirmation', message, [
{text: 'No', onPress: () => resolve(false)},
{text: 'Yes', onPress: () => resolve(true), isPreferred: true},
]),
);
Now just import helper function in any React Native component for delete or submit confirmations:
import { confirm } from './helpers'
return (
<TouchableOpacity
onPress={async () => {
const shouldContinue = await confirm('Do you want to proceed?');
if (shouldContinue) {
// do your thing
}
}}>
<Text>Let's go!</Text>
</TouchableOpacity>
)