Thursday, August 15, 2019

React Native Custom Common Toast for both Android iOS App

This tutorial explains how to create custom toast message in android or ios device in react native application. Toast is the one of the oldest component in android applications history.Toast would only obtain text message and automatically fill on screen according to given message. By default react native Android app supports Toast message but the iOS dose not support Toast. Toast is the one of the oldest component in android applications history. Its been present since the beginning of Android app development and continuously used by millions of developers. Toast is used to give a simple feedback on any given task when the task is completed.

React Native Custom Common Toast for both Android iOS App


Custom Common Toast for both Android iOS in React Native

Lets see the complete source code that helps to create custom toast message in android or ios device in react native application.

project Structure :

Toast.js
This is a custom class that helps to display different type of toast message in react native application.
import React, { Component } from 'react';
import { StyleSheet, Text, Animated } from 'react-native';

import PropTypes from 'prop-types';

export default class Toast extends Component {
   constructor() {
      super();
      this.animateOpacityValue = new Animated.Value(0);
      this.state = {
         ShowToast: false
      }
      this.ToastMessage = '';
   }

   componentWillUnmount() {
      this.timerID && clearTimeout(this.timerID);
   }

   ShowToastFunction(message = "Custom React Native Toast", duration = 4000) {
      this.ToastMessage = message;
      this.setState({ ShowToast: true }, () => {
         Animated.timing
            (
               this.animateOpacityValue,
               {
                  toValue: 1,
                  duration: 500
               }
            ).start(this.HideToastFunction(duration))
      });
   }

   HideToastFunction = (duration) => {
      this.timerID = setTimeout(() => {
         Animated.timing
            (
               this.animateOpacityValue,
               {
                  toValue: 0,
                  duration: 500
               }
            ).start(() => {
               this.setState({ ShowToast: false });
               clearTimeout(this.timerID);
            })
      }, duration);
   }

   render() {
      if (this.state.ShowToast) {
         return (
            <Animated.View style={[styles.animatedToastView, { opacity: this.animateOpacityValue, top: (this.props.position == 'top') ? '10%' : '80%', backgroundColor: this.props.backgroundColor }]}>
               <Text numberOfLines={1} style={[styles.ToastBoxInsideText, { color: this.props.textColor }]}>{this.ToastMessage}</Text>
            </Animated.View>
         );
      }
      else {
         return null;
      }
   }
}

Toast.propTypes = {
   backgroundColor: PropTypes.string,
   position: PropTypes.oneOf([
      'top',
      'bottom'
   ]),
   textColor: PropTypes.string
};

Toast.defaultProps =
   {
      backgroundColor: '#666666',
      textColor: '#fff'
   }

const styles = StyleSheet.create({
   animatedToastView:
   {
      marginHorizontal: 30,
      paddingHorizontal: 25,
      paddingVertical: 10,
      borderRadius: 25,
      zIndex: 9999,
      position: 'absolute',
      justifyContent: 'center'
   },

   ToastBoxInsideText:
   {
      fontSize: 15,
      alignSelf: 'stretch',
      textAlign: 'center'
   }

});

App.js
This is main class that helps to display the toast message when user clicks on button.
import React, { Component } from 'react';
import { StyleSheet, View, Button, Platform } from 'react-native';
import Toast from "./components/Activity/Toast"


export default class App extends Component {

  Default_Toast_Bottom = () => {
    this.refs.defaultToastBottom.ShowToastFunction('Default Toast Bottom Message.');
  }

  Default_Toast_Top = () => {
    this.refs.defaultToastTop.ShowToastFunction('Default Toast Top Message.');
  }

  Default_Toast_Bottom_With_Different_Color = () => {
    this.refs.defaultToastBottomWithDifferentColor.ShowToastFunction('Default Toast Bottom Message With Different Color.');
  }

  Default_Toast_Top_With_Different_Color = () => {
    this.refs.defaultToastTopWithDifferentColor.ShowToastFunction('Default Toast Top Message With Different Color.');
  }

  render() {
    return (
      <View style={styles.MainContainer}>

        <View style={{ marginBottom: 12 }}>
          <Button onPress={this.Default_Toast_Bottom} title="Click Here To Show Default Toast Bottom Message" />
        </View>

        <View style={{ marginBottom: 12 }}>
          <Button onPress={this.Default_Toast_Top} title="Click Here To Show Default Toast Top Message" />
        </View>

        <View style={{ marginBottom: 12 }}>
          <Button onPress={this.Default_Toast_Bottom_With_Different_Color} title="Click Here To Show Default Toast Bottom Message With Different Color" />
        </View>

        <View style={{ marginBottom: 12 }}>
          <Button onPress={this.Default_Toast_Top_With_Different_Color} title="Click Here To Show Default Toast Top Message With Different Color" />
        </View>

        <Toast ref="defaultToastBottom" position="bottom" />
        <Toast ref="defaultToastTop" position="top" />
        <Toast ref="defaultToastBottomWithDifferentColor" backgroundColor='#4CAF50' position="bottom" />
        <Toast ref="defaultToastTopWithDifferentColor" backgroundColor='#E91E63' position="top" />

      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: (Platform.OS == 'ios') ? 20 : 0,
    margin: 10
  },
});

Screenshot :

React Native Custom Common Toast for both Android iOS App

React Native Custom Common Toast for both Android iOS App

React Native Custom Common Toast for both Android iOS App

React Native Custom Common Toast for both Android iOS App

React Native Custom Common Toast for both Android iOS App


This is all about React Native Custom Common Toast for both Android iOS AppThank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment