Open In App

React Native Alert API

In this article, We are going to see how to create an alert in react-native. For this, we are going to use React Native Alert API. It’s basically a small window that pops up to get the user’s choice.

It is an API that uses the alert method to show up the alert dialog box. This dialog box can have three buttons which are positive, negative, and neutral for performing different actions.



Syntax : 

Alert.alert(
      "Alert Title",
      "Alert Msg",
      [
        {
          text: "Cancel"
        },
        { 
          text: "OK"
        }
      ]
);

The React Native alert API accepts two methods as mentioned and described below.



Parameters for alert method: 

Parameters for prompt method: 

Now let’s start with the implementation:

Project Structure:

Example: Now lets implement the alert functionality. Here we created a button and when someone clicks on that button an alert will pop up.




import React from 'react';
import { StyleSheet,
         Text, 
          View,
          Button,
          Alert
        } from 'react-native';
  
export default function App() {
   
  // Alert function
  const alert = ()=>{
    Alert.alert(
      "GeeksforGeeks",
      "How are you!",
      [
        {
          text: "Cancel",
        },
        {
          text: "OK",
        }
      ]
    );
  }
  
  return (
    <View style={styles.container}>
      <Button title={"Click me"} onPress={alert}/>
    </View>
  );
}
  
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

 Start the server by using the following command.

npm run android

Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. 

Reference: https://reactnative.dev/docs/alert


Article Tags :