Alert in React Native with Example

Last updated on Sep 09,2024 82 Views
Experienced tech content writer passionate about creating clear and helpful content for... Experienced tech content writer passionate about creating clear and helpful content for learners. In my free time, I love exploring the latest technology.

Alert in React Native with Example

edureka.co

React Native is a versatile tool that enables the development of applications for Android and iOS manufacturers using JavaScript. Another critical aspect of any mobile app is the option to deliver users’ alerts or notifications on time. In React Native, the Alert component turns out to be very useful in performing this task. So here, in this article, we will talk about Alert in React Native in detail, from how it functions, the various settings you can put it through, and how you can implement this in both iOS and Android applications using React Native.

What is the Alert?

An alert is a window that appears on the screen when something happens as a result of a specific action in the app or as a reaction to an inside app action to notify the user or give them particular instructions. In React Native, the Alert component is one of the most straightforward yet flexible components that can be used primarily to show alerts with any kind of message along with the buttons.

The alerting mechanism is primarily used to capture the user’s attention that something is essential and should be noticed as soon as possible. Notifications are applied in cases like checking the actions of a user (e.g., deleting a file), displaying a message about an error, or a message about an update is to be made.

When using the Alert in React Native, one can use several built-in methods to develop various types of alerts, ranging from simple alerts to advanced alerts, alerts with buttons, and many others.

Buttons in Alert

The Alert component in React Native also provides the provision to include one or more buttons on the alerts so that the users can choose their response. Depending on the user’s selection, these buttons can be programmed to take some action. 

There is an alert with the Ok and Cancel buttons below the message. 

Here is an example of a simple alert with two buttons:

import { Alert } from 'react-native';
Alert.alert(
  "Alert Title",
  "My Alert Message",
  [
    {
      text: "Cancel",
      onPress: () => console.log("Cancel Pressed"),
      style: "cancel"
    },
    { text: "OK", onPress: () => console.log("OK Pressed") }
  ],
  { cancelable: false }
);

In this example: 

The two buttons look like this. The first button shows the message “Cancel.” When selected on this button, the console log ‘Cancel’ will appear. 

As with the first button, the second button is labeled “OK,” and its function is different when clicked.

The cancelable option means the alert cannot be closed by clicking anywhere outside.

This alert is for the React Native framework and can be seen in iOS. 

iOS alerts have a certain appearance as they follow Apple Human Interface Guidelines. When using the Alert component in the React Native platform, then the appearance of an alert in iOS is an out-of-the-box solution provided by the platform. 

React Native Alert in iOS

Even though the default behavior of alerts is the same for all platforms, you may want to change something in the iOS version of the alert. For instance, iOS alerts allow for the inclusion of a cancel button, which is of a different style from other buttons.

It is possible to set the style within the button configuration using the style property, as shown earlier. iOS also offers more specializations, for instance, to add a text field in the alert view, but this is done with special implementations.

React Native Alert in Android

In Android, Alert is created by using React Native. 

On Android, alerts reflect the Material Design generalizing iOS alerts called ‘dialogs.’ In React Native, navigating the Alert component is very smooth and works in conjunction with the dialog system in Android.

Similar to the iOS implementation, there are similar features in Android, but you can also customize them further, such as the layout of the alerts, the buttons used, and more. For example, Android alerts offer the ability to distinguish between positive buttons, negative buttons, and neutral ones. 

Here’s an example of an Android-specific alert configuration:

import { Alert, Platform } from 'react-native';
if (Platform.OS === 'android') {
  Alert.alert(
    "Android Alert",
    "This is an Android-specific alert",
    [
      { text: "Maybe Later", onPress: () => console.log("Maybe Later Pressed") },
      { text: "Cancel", onPress: () => console.log("Cancel Pressed"), style: "cancel" },
      { text: "OK", onPress: () => console.log("OK Pressed") }
    ]
  );
}

This code makes the alert appear only on Android devices; it has 3 buttons with different actions correspondingly.

React Native Alert Example

To provide a comprehensive understanding of how to use alerts in React Native, let’s look at a full example that includes various alert types and configurations:

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


const App = () => {


  const showAlert = () => {
    Alert.alert(
      "Alert Title",
      "This is a simple alert",
      [
        { text: "Ask me later", onPress: () => console.log("Ask me later pressed") },
        { text: "Cancel", onPress: () => console.log("Cancel Pressed"), style: "cancel" },
        { text: "OK", onPress: () => console.log("OK Pressed") }
      ]
    );
  };


  return (
    <View style={{ marginTop: 50 }}>
      <Button title="Show Alert" onPress={showAlert} />
    </View>
  );
};

export default App;

 In this example, pressing the “Show Alert” button triggers an alert with three options: There are ‘Ask me later’, ‘Cancel’, and ‘OK’ buttons. Each button is a function that will perform a particular action, as illustrated in the console logs. 

Output:

Conclusion

Alerts are an essential feature of any kind of mobile application since they allow simply notifying users and requesting their action. The alert component of React Native provides an essential and versatile way of developing alerts that effectively function in both the iOS and Android platforms. For simple alerts or when you want to display a dialog with several choices using multiple buttons, React Native has given you the means to achieve this.  

If you want to do more complex cases, it is possible to add complex pop-ups, custom modal dialogs, or utilize third-party libraries to expand the functionality of your alerts. When using these tools, you can be certain that your app is making the right output for the right audience, informing the users, and giving them the most appropriate choices to meet their needs. 

For those who want to learn more about the next level of React, it is recommended that you attend a React Js Course, in which you will be able to learn how to create a more effective and interactive UI with the help of React.

FAQs

The Alert. alert() function in React Native is employed to display an alert dialog that comes with a title, a message, and buttons. This is a type of method that does not change the state of the application that Alert API provokes; therefore, it is exceptionally simple to call from any part of the application.

To invoke an alert in React Native, you can use Alert. The alert() function requires a title, message, and an array of buttons as the parameters. This method is usually called when called by another event, such as a button push.

 Alert with two buttons is the alert dialog in React Native capable of showing the users two options to select from. Every button can have different labels and linked actions, and it is possible to set style and interaction.

SweetAlert is the other library most often used to develop more beautiful alerts. However, SweetAlert is not a component of the React Native package in its simplest form. If you want to achieve a similar functionality, you have to build your own components, or if you want to get a more customized view for an alert, you can use react-native-modal or react-native-flash-message.

Upcoming Batches For React JS Training Course Online
Course NameDateDetails
React JS Training Course Online

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework