How to show an alert in React Native

Alert is a React API that allows us to generate a dynamic alert message in our project. It provides textual feedback messages for typical user actions with flexible choices. It has a specified title and message.

Usually, an alert has buttons that will reflect the change in the function's onPress call. By default, an "OK" button is displayed. When pressed, it will dismiss the alert.

Static alertsAlerts that only prompts the given message. work on both Android and iOS. At the same time, alerts that ask to enter some information are available only on iOS.

Note:

“react-native”: “https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz

“react-native-web”: “~0.13.12”

Generating alerts in React Native

We can create different types of alerts in React Native:

  • A Single option to click and dismiss.

  • Two options like "OK" and "Cancel".

  • An alert with more options.

Example 1

We can generate a simple alert using the following method:

{
  "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
  "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
}
Code for single option alert

Explanation

  • Lines 12: We import React and some React Native components. For example, Button and Alert are built-in components used to generate an alert in React Native.

  • Lines 4–7: We create a function simpleAlert inside the functional component App, which returns the alert message.

  • Lines 8–16: We have the return part of the above component in which we write the HTML code. We create a button, and in its onPress call, we call the simpleAlert function.

  • Lines 20–26: We create a StyleSheet object named styles using StyleSheet.create in which we have defined all our CSS in a container. We can use it anywhere using the class name styles.container in line 10.

Example 2

We can generate a two-option alert using the following method:

{
  "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
  "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
}
Code for two-option alert

Explanation

  • Lines 4–7: We create a function simpleAlert inside the functional component App, which returns the alert message.

  • Lines 8–16: Here, we have the return part of the above component in which we write the HTML code. We create a button, and in its onPress call, we call the simpleAlert function.

  • Lines 20–26: We create a Stylesheet object using StyleSheet.create named styles in which we define all our CSS in a container. We can use it anywhere by using the class name styles.container in line 10.

Output

The output of both examples in the emulator is as follows:

Button for simple alert
1 of 4

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved