React Native Alert Example – Show Alert in React Native App

Last Updated on by in React Native
This tutorial shows you how to easily show an alert message in React Native application using the React Native Alert API. We will also learn to create custom alert using React Native Awesome Alerts module.Show Alert in React Native App

The Alert dialog is used to show the message to the user. Usually, it is a dialog or popup that appears with a message and title on clicking on a button or loading or redirecting to a particular page in an application.

Alerts dialog intervenes with users with essential information, details, or actions. The Alert API efficiently works on both iOS and Android and can show static alerts.

React Native offers three types of Alert dialog, and those are Simple Alert, Two Options Alert, and Three Options Alert.

iOS Alert

On iOS, you can specify as many buttons as you want. Each button can optionally define a style, which is one of “default” and “cancel”.

Android Alert

You can define only 3 buttons on Android Alert dialog. There is a provision of a negative, positive, and neutral button on Android.

Only one button is considered to be positive, and it’s button’s value will be “Ok”.

Alert with two buttons will be followed by “Cancel” and “Ok” in Android.

Alert with three buttons will be followed by “Ask Me Later”, “Cancel” and “OK” values.

Prerequisite

The following tools, frameworks, and packages are required to get started.

  • Node.js
  • NPM
  • IDE
  • React-Native
  • React-Native CLI
  • Xcode for iOS
  • Android Studio

Install React Native Project via React Native CLI

Install React Native CLI globally on your system.

npm install -g react-native-cli

Install fresh React Native application from scratch.

react-native init rnalert

Get inside the project folder.

cd rnalert

Check installed version of React Native.

react-native -v

# react-native-cli: 2.0.1
# react-native: 0.61.5

React Native Alert Example

First, we have to import Alert API to show an Alert message with one, two, and three buttons.

import { Alert, Button, View, StyleSheet } from 'react-native';

Next, we define Alert.alert() function inside the react-native App Component. These Alert popups show alert messages with one, two, and three buttons.

We pass the first argument to define the title for alert, second for the alert message, third for onPress() event for buttons.

If the ‘cancelable’ property is set to true, this will not cancel or close the alert when clicked outside of the alert. Same way if cancelable false is set initially, then the popup will be canceled when clicked outside.

export default class App extends Component {
  
  openAlert=()=>{
    alert('Alert with one button');
  }
  
  openTwoButtonAlert=()=>{
    Alert.alert(
      'Hey There!',
      'Two button alert dialog',
      [
        {text: 'Yes', onPress: () => console.log('Yes button clicked')},
        {text: 'No', onPress: () => console.log('No button clicked'), style: 'cancel'},
      ],
      { 
        cancelable: true 
      }
    );
  }
  
  openThreeButtonAlert=()=>{
    Alert.alert(
      'Hey There!', 'Three button alert dialog',
      [
        {text: 'Ask me later', onPress: () => console.log('Later button clicked')},
        {text: 'Yes', onPress: () => console.log('Yes button is clicked')},
        {text: 'OK', onPress: () => console.log('OK button clicked')},
      ],
      { 
        cancelable: false 
      }
    );
  }

}

Now, create the buttons to show the Alert dialog in the view inside the render() method in App component function.

render() {
    return (
      <View style={styles.mainWrapper}>
        <Button title='1 button alert' onPress={this.openAlert}/>

        <Button title='2 buttons alert' onPress={this.openTwoButtonAlert}/>

        <Button title='3 buttons alert' onPress={this.openThreeButtonAlert}/>
      </View>
    );
  }

Let’s add a little bit of style. The const styles stylesheet.create() method allows adding styling in the react-native app.

const styles = StyleSheet.create({
  mainWrapper: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection:'row',
  }
});

Here, is the final code that is defined in the App.js file.

import React, { Component } from 'react';
import { Alert, Button, View, StyleSheet } from 'react-native';


export default class App extends Component {
  
  openAlert=()=>{
    alert('Alert with one button');
  }
  
  openTwoButtonAlert=()=>{
    Alert.alert(
      'Hey There!',
      'Two button alert dialog',
      [
        {text: 'Yes', onPress: () => console.log('Yes button clicked')},
        {text: 'No', onPress: () => console.log('No button clicked'), style: 'cancel'},
      ],
      { 
        cancelable: true 
      }
    );
  }
  
  openThreeButtonAlert=()=>{
    Alert.alert(
      'Hey There!', 'Three button alert dialog',
      [
        {text: 'Ask me later', onPress: () => console.log('Later button clicked')},
        {text: 'Yes', onPress: () => console.log('Yes button is clicked')},
        {text: 'OK', onPress: () => console.log('OK button clicked')},
      ],
      { 
        cancelable: false 
      }
    );
  }

  render() {
    return (
      <View style={styles.mainWrapper}>
        <Button title='1 button alert' onPress={this.openAlert}/>

        <Button title='2 buttons alert' onPress={this.openTwoButtonAlert}/>

        <Button title='3 buttons alert' onPress={this.openThreeButtonAlert}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  mainWrapper: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection:'row',
  }
});

Create Custom Alert in React Native

We can also create a custom alert in react native using react-native-awesome-alerts npm package.

Install package using following command.

npm i react-native-awesome-alerts

Here, is the code that goes directly to App.js file or in whichever page you intend to create custom alert dialog.

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import AwesomeAlert from 'react-native-awesome-alerts';
 

export default class App extends Component {
 
  constructor(props) {
    super(props);
    this.state = { showAlert: false };
  };
 
  showAlert = () => {
    this.setState({
      showAlert: true
    });
  };
 
  hideAlert = () => {
    this.setState({
      showAlert: false
    });
  };
 
  render() {
    const {showAlert} = this.state;
 
    return (
      <View style={styles.container}>
 
        <Text>Super Cool Alert</Text>
        <TouchableOpacity onPress={() => {
          this.showAlert();
        }}>
          <View style={styles.button}>
            <Text style={styles.text}>Click Please!</Text>
          </View>
        </TouchableOpacity>
 
        <AwesomeAlert
          show={showAlert}
          showProgress={false}
          title="Cool Alert"
          message="I Got a message!"
          closeOnTouchOutside={true}
          closeOnHardwareBackPress={false}
          showCancelButton={true}
          showConfirmButton={true}
          cancelText="No, cancel"
          confirmText="Yes, delete it"
          confirmButtonColor="#008080"
          onCancelPressed={() => {
            this.hideAlert();
          }}
          onConfirmPressed={() => {
            this.hideAlert();
          }}
        />
      </View>
    );
  };
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ffffff',
  },
  button: {
    padding: 15,
    margin: 15,
    borderRadius: 4,
    backgroundColor: "#3740ff",
  },
  text: {
    color: '#fff',
    fontSize: 16
  }
});

React Native Awesome Alerts is easy to use and best for creating custom alerts. It provides tons of features that allow you to modify the alert dialog to the next level. It will enable you to add custom style in alert, change, or update the alert button colors easily.

Run React Native App

Next, to show a native alert in react application. Go to your terminal and run either of the commands based on your device preference.

To start the app on an Android Virtual Device.

react-native run-android

To start the app on an iOS Virtual Device.

react-native run-ios

Conclusion

Finally, Alert Dialog tutorial is over, I believe you must have a better understanding of showing Alert dialog in React Native app. We also learned to create custom alert dialog box in react native application.

You can check the above alert example in iOS and Android simulators.

Get the full code of this tutorial on this git repository.

Happy Coding!