Alert in React Native

Learn how to display and customize an Alert in your React Native application with our comprehensive tutorial.

In this tutorial, we'll show you how simple it is to display and customize an alert in React Native.

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

iOS Screenshot with the device frame showing confirmation 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.

iOS Screenshot with the device frame showing different alert button styles

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>
)

We hope you enjoyed this content and now better understand how to use Alert in React Native.

Never miss a beat

Stay in the loop with our latest updates and offers - no spam, just the good stuff!