Sunday, October 14, 2018

Create Custom Snackbar Component Example In React Native- Android

This tutorial explains how to create simple Snackbar component in react native application. Snackbars are just like Toast messages except they provide action to interact with. Snackbar will be displayed at the bottom of the screen and can be swiped off in order to dismiss them.
Create Custom Snackbar Component Example In React Native- Android
In this example, when user clicks on "Show Snackbar" Button component, then it will display Snackbar and show messages in the bottom of the application with swiping enabled. Also it is display "UNDO" text message at right position of Snackbar, when user clicks on "UNDO" text, then it will hide or dismiss the Snackbar.

React Native Snackbar Example Android :

Project Structure :
Lets see the project structure.
Create Custom Snackbar Component Example In React Native- Android

Lets follow the below steps to create Snackbar like toast message in React Native.



Step-1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step-2: Create component folder inside the main project directory and inside that create Snackbar component. This component will display snackbar message at bottom of the screen.
  • ShowSnackBarFunction : This function will display the snackbar message, when user call this function.
  • hide : This function automatically called at specified timeinterval(i.e 3000 miliseconds) and hide the snackbar.
  • SnackBarCloseFunction : This function helps to hide snackbar, when user clicks on UNDO Text message present inside the snackbar.

Complete source code for Snackbar Component.

Snackbar.js
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from "react";
import { StyleSheet, Text, View, Animated } from "react-native";


class SnackBar extends Component
{
   constructor() {
   super();

   this.animatedValue = new Animated.Value(50);
   this.ShowSnackBar = false;
   this.HideSnackBar = true;
   this.state = {
     SnackBarInsideMsgHolder: ''
   };
 }

  ShowSnackBarFunction(SnackBarInsideMsgHolder="Default SnackBar Message...", duration=3000)
  {
    if( this.ShowSnackBar === false )
    {
      this.setState({ SnackBarInsideMsgHolder: SnackBarInsideMsgHolder });

      this.ShowSnackBar = true;

      Animated.timing
      (
          this.animatedValue,
          {
              toValue: 0,
              duration: 400
          }
      ).start(this.hide(duration));
    }
  }

    hide = (duration) =>
    {
      this.timerID = setTimeout(() =>
      {
        if(this.HideSnackBar === true)
        {
            this.HideSnackBar = false;

            Animated.timing
            (
              this.animatedValue,
              {
                toValue: 50,
                duration: 400
              }
            ).start(() =>
            {
              this.HideSnackBar = true;
              this.ShowSnackBar = false;
              clearTimeout(this.timerID);
            })
        }
      }, 10000);
    }

    SnackBarCloseFunction = () =>
    {
      if(this.HideSnackBar === true)
      {
          this.HideSnackBar = false;
          clearTimeout(this.timerID);

          Animated.timing
          (
              this.animatedValue,
              {
                toValue: 50,
                duration: 400
              }
          ).start(() =>
          {
              this.ShowSnackBar = false;
              this.HideSnackBar = true;
          });
      }
    }

    render()
    {
      return(

         <Animated.View style = {[{ transform: [{ translateY: this.animatedValue }]}, styles.SnackBarContainter ]}>

            <Text numberOfLines = { 1 } style = { styles.SnackBarMessage }>{ this.state.SnackBarInsideMsgHolder }</Text>

            <Text style = { styles.SnackBarUndoText} onPress = { this.SnackBarCloseFunction } > UNDO </Text>

         </Animated.View>

      );
    }
}

export default SnackBar;


const styles = StyleSheet.create({

  SnackBarContainter:
  {
    position: 'absolute',
    backgroundColor: '#009688',
    flexDirection: 'row',
    alignItems: 'center',
    left: 0,
    bottom: 0,
    right: 0,
    height: 50,
    paddingLeft: 10,
    paddingRight: 55
  },

  SnackBarMessage:
  {
    color: '#fff',
    fontSize: 18
  },

  SnackBarUndoText:{
    color: '#FFEB3B',
    fontSize: 18,
    position: 'absolute',
    right: 10,
    justifyContent: 'center',
    padding: 5

  }
});

Step-3: Open index.android.js  / index.ios.js  in your favourite code editor and erase all code and follow this tutorial.

Step-4: Through react , react-native  packages import all required components. Also import the above Snackbar Component inside this react native project.
import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, Button, Image, Animated } from "react-native";
import SnackBar from './component/SnackBar'

Step-5 : Create DisplaySnackBar method inside the HomeActivity class and this function helps to pass the custom text message to Snackbar Component.
DisplaySnackBar = () => {
    this.refs.ReactNativeSnackBar.ShowSnackBarFunction("Snackbar example");
  };

Step-6 : Implement render method and return Button and SnackBar component wrapped by root View component.
render() {
    return (
      <View style={styles.container}>

        <Button onPress={this.DisplaySnackBar} title=" Show SnackBar ">
        </Button>

        <SnackBar ref="ReactNativeSnackBar" />
      </View>
    );
  }
}

Step-7 : Apply the below style sheet design.
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    backgroundColor: "#e5e5e5"
  }
});

Complete Source Code for App.js 

Lets see the complete source code that helps to display Snackbar like toast message in react native application.
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from "react";
import {  Platform,  StyleSheet,  Text,  View,  Button,  Image,  Animated} from "react-native";
import SnackBar from "./component/SnackBar";

export default class HomeActivity extends Component {


  DisplaySnackBar = () => {
    this.refs.ReactNativeSnackBar.ShowSnackBarFunction("Snackbar example");
  };

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

        <Button onPress={this.DisplaySnackBar} title=" Show SnackBar ">
        </Button>

        <SnackBar ref="ReactNativeSnackBar" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    backgroundColor: "#e5e5e5"
  }
});

Screenshot :

Create Custom Snackbar Component Example In React Native- Android

Create Custom Snackbar Component Example In React Native- Android

This is all about Snackbar like toast message in react native applicationThank 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.



1 comment: