CodeBlanks Logo Icon CodeBlanks

Alert

Learn to show alerts with Alert.alert.

What is Alert?

In React Native the simplest way to show a quick warning to the user is Alert.alert. This function opens a modal dialog box in the center of the screen. It blocks interaction with other screen elements until the user presses a button.

Alert.alert takes three parameters: title, message and a buttons array. In the simplest usage you provide only the title: Alert.alert('Saved'). Message and buttons are optional; you add them as needed.

Alert.alert syntax

The full form of the Alert.alert call is: Alert.alert(title, message, buttons). The title is a string, the message is a string, and the buttons is an array of objects. If no buttons are provided a single OK button appears by default.

Alert.alert(
  'Delete file?',
  'This action cannot be undone.'
);

This example has only title and message; the default OK button is added automatically. You must import Alert from the react-native package.

Practice Your turn: show an alert

Import Alert from react-native. When a button is pressed call Alert.alert('Record deleted', 'Cannot be undone').

Starter code

App.js
import { Button } from 'react-native';

function Screen() {
  return (
    <Button
      title="Delete"
      onPress={() => {
        // show an alert
      }}
    />
  );
}

Sample solution

App.js
import { Alert, Button } from 'react-native';

function Screen() {
  return (
    <Button
      title="Delete"
      onPress={() => Alert.alert('Record deleted', 'Cannot be undone')}
    />
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the minimum number of parameters for Alert.alert?

App.js
Alert.alert('Saved')
  • Only one: title Correct answer
  • At least two: title and message
  • With no parameters at all
  • At least three: title, message, buttons

Explanation: Only the title is required; message and buttons are optional.

2 Fill in the blank: Alert call

Question
Alert.____('Warning', 'File saved');
Answer
Alert.alert('Warning', 'File saved');

Explanation: You show an alert with Alert.alert.

3 Match: Alert parameters

Term Meaning
title first parameter
message second parameter
buttons third parameter

All lessons in Beginner