Knowledge Share Helps you in some way
Custom flash message in react native

Custom flash message in react native

Monday, 7 August 2023 |

Implementing flash alert message in React Native

In the realm of mobile app development, creating a seamless and engaging user experience is paramount. React Native, a popular framework for building cross-platform mobile applications, offers developers the flexibility to craft dynamic and interactive interfaces. One essential component of a user-friendly interface is providing informative feedback to users regarding their actions or system events. Custom flash messages serve as an effective means to deliver such feedback, offering developers the opportunity to enhance user interaction within their React Native applications.

Custom flash messages, also known as toast notifications or snackbar alerts, are temporary visual cues that appear on the screen to convey important information to the user. Unlike standard system alerts, which can be generic and intrusive, custom flash messages allow developers to tailor the message content, styling, and behavior to suit the application's design language and user preferences.

Implementing custom flash messages in React Native involves several key steps. Firstly, developers need to design the visual appearance of the flash message, considering factors such as color scheme, typography, and animation effects. Next, they must create components or functions to handle the display logic and manage the lifecycle of the flash messages, including triggering their appearance and dismissal based on user actions or system events.

Furthermore, custom flash messages should offer flexibility in terms of positioning on the screen, allowing developers to choose whether messages appear at the top, bottom, or center of the viewport. Additionally, developers may incorporate features such as duration control, allowing messages to automatically disappear after a specified time interval, or user interaction capabilities, enabling users to dismiss messages manually.

Post Video: Custom flash message React native

By integrating custom flash messages into React Native applications, developers can significantly improve the user experience by providing timely and contextually relevant feedback. Whether it's confirming a successful action, alerting users to errors or warnings, or prompting them for further action, custom flash messages empower developers to communicate effectively with their audience and create a more intuitive and engaging mobile app interface.

In this article , I will show you how you can add custom flash message or create a component class to display flash message using react native. As your can see in Post Video section , there are two screen , one is for changning your password and one is for uploading your profile photo , so they both screen call API using Axios of react native. So when you click on save button of both screen , API get call and check the form with server side validation if form is proper filled or not.You can use any framwork like laravel , codeigniter to create API. FlashMessageComponent is a good class which holds two state as flashMessage and isflashMessage flashMessage will store string message from api and isflashMessage is a flag as value will be either true or false , and functions as showFlashMeg and closeFlashMessage will set the message string and time out in milisecond & closeFlashMessage will clear state.

									     import React, { Component } from 'react';
import { Text, View, TouchableOpacity, Image, StyleSheet } from 'react-native';
export default class FlashMessageComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      flashMessage: false,
      isflashMessage: false,
    }
  }
  showFlashMeg(msgflash, timeoutno) {
    this.setState({
      isflashMessage: true,
      flashMessage: msgflash
    }, () => { setTimeout(() => this.closeFlashMessage(), timeoutno) })
  }
  closeFlashMessage() {
    this.setState({
      isflashMessage: false,
      flashMessage: false
    })
  }
  render() {
    return (
      <View>
        {
          this.state.isflashMessage == true ?
            <View style={styles.scrollboxActionContainer}>
              <View style={styles.scrollboxActionContainerInner} >
                <View style={styles.scrollboxHorizontal}>
                  <View style={styles.flashMessage}>
                    <Text style={styles.flashMessageHeading}>
                      Alert Notification
                    </Text>
                    <Text>
                      {this.state.flashMessage}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
            :
            null
        }
      </View>
    );
  }
}
const styles = StyleSheet.create({
  scrollboxActionContainer: {
    backgroundColor: '#fff',
    marginHorizontal: 10,
    justifyContent: 'center',
    marginTop: Platform.OS === 'ios' ? '2%' : '3%',
    zIndex: 1,
    marginBottom: Platform.OS === 'ios' ? '2%' : '3%',
  },
  scrollboxActionContainerInner: {
    backgroundColor: '#fff'
  },
  scrollboxHorizontal: {
    flex: 1,
    backgroundColor: '#fff',
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 2, height: 2 },
    shadowOpacity: 0.4,
    shadowRadius: 2,
    elevation: 3,
    paddingTop: '10%',
  },
  flashMessage: {
    flex: 1,
    position: 'absolute',
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    top: 0,
    zIndex: 1,
    backgroundColor: '#edca82',
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 2, height: 2 },
    shadowOpacity: 0.4,
    shadowRadius: 2,
    elevation: 3,
    padding: 5,
  },
  flashMessageHeading: {
    fontWeight: 'bold',
    fontSize: 12,
  }
})										
									

Now how you use it like you can see in Post Video section , so below is a profile photo tab screen react native class, the main purpose of this class is to browse photo and upload to server by using Axios. You can see in below class that we have imported the FlashMessageComponent class. Now , you imported the class , then how to access the function of above class in another class for achieving this this.FlashMessageComponent = React.createRef(); we have to create a reference or register in constructor of base class.

axiosFlashMessageTimeOut is just milisecond you want to set for flash message auto close time. Just created a constant file and declare there. You can also use or set it for displaying any kind of information or notification.

									     import React from 'react';
import {
  Text,  View, TouchableOpacity, SafeAreaView, Dimensions
} from 'react-native';
import HeaderComponent from './../../components/HeaderComponent';
import FlashMessageComponent from './../../components/FlashMessageComponent';
import { apiUrl, netErrorMsg, axiosFlashMessageTimeOut, alertInfoMessageTimeOut, axiosHeaders } from "./../../config/constant";
const axios = require('axios');
const auth = {
  headers: axiosHeaders
};
const dimensions = Dimensions.get('window');
const imageHeight = Math.round(dimensions.width * 9 / 16);
const imageWidth = dimensions.width;

export default class ProfilePhotoScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: false,
      loading: false,
      userId: '',
      image: null,
      browseornot: false,
    }
    this.FlashMessageComponent = React.createRef();
  }
  componentDidMount() {
    this._bootstrapAsync();
  }
  componentWillUnmount() {
    this.FlashMessageComponent;
  }
  doSaveProfilePhoto() {
    if (!this.state.loading) {
      this.setState({
        loading: true
      });
      if (this.state.browseornot === false) {
        this.FlashMessageComponent.current.showFlashMeg('Browse your profile photo first then save it.', axiosFlashMessageTimeOut);
        this.setState({ loading: false });
        return;
      }
      axios.post(apiUrl + 'user/saveprofilephoto', formData, auth).then(response => {
        if (response.data.status == 1) {
          this.FlashMessageComponent.current.showFlashMeg(response.data.msg, axiosFlashMessageTimeOut);
        } else {
          this.FlashMessageComponent.current.showFlashMeg(response.data.msg, axiosFlashMessageTimeOut);
        }
        this.setState({ loading: false });
      }).catch(error => {
        if (error.response.data.status == 1) {
          this.FlashMessageComponent.current.showFlashMeg(error.response.data.msg, axiosFlashMessageTimeOut);
        } else {
          this.FlashMessageComponent.current.showFlashMeg(error.response.data.msg, axiosFlashMessageTimeOut);
        }
        this.setState({ loading: false });
      });
    }
  }
  render() {
    let { image } = this.state;
    return (
      <SafeAreaView style={styles.mainContainer}>
        <View style={styles.mainContainer}>
          <HeaderComponent {...this.props} showName="Change Your Profile Photo" />
          <YourAccountLink navigation={this.props.navigation} />
          <View style={styles.scrollboxActionContainer}>
            <View style={styles.scrollboxActionContainerInner} >
              <View style={styles.scrollboxHorizontal}>
                <View style={styles.buttonContainer}>
                  <View style={styles.buttonBodyImage}>
                    <TouchableOpacity onPress={
                      () => this._pickImage()}>
                      <Text style={styles.buttonTextImage}>Click here to browse...</Text>
                    </TouchableOpacity>
                  </View>
                </View>
                <View style={styles.buttonContainer}>
                  <View style={styles.buttonBody}>
                    <TouchableOpacity onPress={
                      () => this.doSaveProfilePhoto()}>
                      <Text style={styles.buttonText}>Save</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
            </View>
          </View>
          <FlashMessageComponent ref={this.FlashMessageComponent} />
        </View>
      </SafeAreaView >
    );
  }
}										
									

React Native