Showing Alert and Toast - React Native

Hey Guys!! Good Day!!!

Hope you all are doing fine! Today let's learn about showing Toast message and Alert in React Native. These two components are some of the most important UI Components. So let's learn in detail.

Alert:

It displays an alert dialog with title and message. We can also add buttons to it to perform click operation, which in turn, fires onPress() event.

In IOS, we can have any no. of buttons in it. But in Android, we can atmost have only 3 buttons. i.e., one Positive button(like 'Ok'), one negative button(like 'Cancel') and one neutral button(like 'Later').

Also In Android, by default, the alert will be dismissed by tapping outside of the 'Alert'. At that time, the event onDismiss() will be fired, where we can do any operation we need. In case, if you don't need that dismissible functionality, you can disable it by adding, { cancellable: false }

Alert.alert('Title', 'Message here', [buttons], {type});

Button order will be taken as follows, depends on button count:
  1.  One button - It will be taken as 'positive' one
  2.  Two buttons - It will be taken in order 'negative' and 'positive' 
  3.  Three buttons - It will be taken in order, 'neutral', 'negative' and 'positive'.

                                       Alert.alert('Success', 'Alert is showing now!!,
                                       [
                                             { text: 'Later' },
                                             { text: 'Cancel' }, 
                                             { text: 'OK' }
                                       ],
                                       { onDismiss : () => { console.log('Dismissed!') }});

Toast:

Sometimes,we just want to display the information, but not as the Alert, at that time Toast is very useful. But it is available only for Android as ToastAndroid Component. If you would like to show Toast in both IOS and Android, you can use any external library for that.

I found a simple library for Toast, Easy Toast.

ToastAndroid can be used in following ways:
  • show - to set message and duration 
  • showWithGravity - to specify gravity, i.e., ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER
  • showWithGravityAndOffset - to specify offset. These offset values will be translated to pixels.
                                    ToastAndroid.show('Normal Toast!, ToastAndroid.SHORT)

                                    * ToastAndroid.showWithGravity('Toast with Gravity!, 
                                                     ToastAndroid.SHORT, ToastAndroid.CENTER)

                                    * ToastAndroid.showWithGravityAndOffset('Toast 
                                                            with Offset!,ToastAndroid.SHORT, 
                                                              ToastAndroid.TOP, 20,50)

Implementation:

Alert will be shown while clicking on Text, 'Show Dialog'. For that onPress() callback is used. Alert can be dismissed while clicking outside of it in Android. While its getting dismissed, let's show a Toast. That's it!!

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Alert,
  ToastAndroid,
} from 'react-native';
import { Constants } from 'expo';

export default class App extends Component {
  onPressed = () => {
    Alert.alert(
      'Success!',
      'My Alert is working fine!!',
      [
        {
          text: 'Later',
          onPress: () => console.log('Ask me later pressed'),
        },
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        { text: 'OK', onPress: () => console.log('OK Pressed') },
      ],
      {
        onDismiss: () => {
          ToastAndroid.showWithGravity(
                'Alert Dismissed with Toast in Android!!',
                ToastAndroid.SHORT,
                ToastAndroid.CENTER
              );
        },
      }
    );
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph} onPress={this.onPressed}>
          Show Alert
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: '#34495e',
  },
});

Run Application:

In IOS:


 

In Android:

 

Custom Dialog:

Sometimes, we may need to create custom dialog in real-time applications. In that case , we can use Modal to do that.


import React from 'react';
import {
  Modal,
  View,
  StyleSheet,
  Text,
  ActivityIndicator
} from 'react-native';

const ProgressDialog = ({ visible }) => (
  <Modal
    visible={visible}
  >
    <View style={styles.container}>
      <View style={styles.content}>
        <Text style={styles.title}>Please Wait</Text>
        <View style={styles.loading}>
          <View style={styles.loader}>
            <ActivityIndicator size="large"  color='white' />
          </View>
          <View style={styles.loadingContent}>
            <Text style={styles.loadingText}>Loading</Text>
          </View> 
        </View>
      </View>
    </View>
  </Modal>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
  },
  content: {
    padding: 35,
    backgroundColor: 'rgba(0, 0, 0, .5)'
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color:'white',
    marginBottom:10
  },
  loading: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  loader: {
    flex: 1,
  },
  loadingContent: {
    flex: 3,
    fontSize: 16,
    paddingHorizontal: 10,
  },
  loadingText:{
     color:'white',
     marginLeft:5
  }
})

export default ProgressDialog;


Now we have learnt to create Toast, Alert and Custom Dialog in React Native. In next post, let's learn about some other interesting topic. Until then, Bubyeee!!! Happieee Coding!!!

Comments

  1. Great blog.
    The information that you shared with your blog about sharing alert and toast in react native is really very specific and knowledgeable. It is very useful to understand the concept of react native.
    I was searching for the best react native app development company India and got this blog.
    Thanks for sharing such a great blog.

    ReplyDelete
  2. The post you shared is great . This is very helpful for the react native app development company in usa . Thanks for the post and keep sharing such information .

    ReplyDelete
  3. AldaimSolutions as an offshore e-Commerce website development company provides a wide range of online business solutions in web and mobile space.Popular rails gemsRails is basically a web application framework, which is consist of everything needs to create database baked web application. It helps the developers to create websites and applications by providing structures for all codes written by them. Moreover, common repetitive tasks are simplified with the help of this technology.
    Best Ecommerces Company Audacity24
    Websites made with PHP and Shopify
    Best ruby gems 2019
    React native and React Js
    Node Js and React Js

    ReplyDelete
  4. Thanks, For Amazing blog and sharing more useful information. discoverer one of the Why React Native is a Good Choice for iOS App Development in India

    ReplyDelete

Post a Comment

Popular posts from this blog

FlatList - PullToRefresh, Load More and Filtering implementation

AsyncStorage in React Native

FlatList - HorizontalList and GridList