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.
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
}
Explanation
Lines 12: We import React and some React Native components. For example,
ButtonandAlertare built-in components used to generate an alert in React Native.Lines 4–7: We create a function
simpleAlertinside the functional componentApp, 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
onPresscall, we call thesimpleAlertfunction.Lines 20–26: We create a
StyleSheetobject namedstylesusingStyleSheet.createin which we have defined all our CSS in a container. We can use it anywhere using the class namestyles.containerin line 10.
Example 2
We can generate a two-option alert using the following method:
{
"12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
"40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
}
Explanation
Lines 4–7: We create a function
simpleAlertinside the functional componentApp, 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
onPresscall, we call thesimpleAlertfunction.Lines 20–26: We create a
Stylesheetobject usingStyleSheet.createnamedstylesin which we define all our CSS in a container. We can use it anywhere by using the class namestyles.containerin line 10.
Output
The output of both examples in the emulator is as follows:
Free Resources