Add Online/Offline Animated Notification to React Native App

In this tutorial we will add online/offline animated notification to our shopping cart app. It’s important to notify user when they go offline, because, your app won’t work same way when its not connected to Internet. Further,  we will keep the online/offline status in redux store so that we can make all components aware when the app goes offline. So, lets get started.

First, we will add an action type in constants>>ActionTypes.js :

export const CHECKNETSTATUS = 'CHECKNETSTATUS'

Next, we will add action and action creator to our actions>>index.js

import * as types from '../constants/ActionTypes'

const netstatus = (status) => ({
  type: types.CHECKNETSTATUS,
  status
})

export const updateNetstatus = (status) => dispatch => {
    dispatch(netstatus(status))
}

In the above code, we have action creator, to make a dispatch, whenever the status of app changes from online to offline or from offline to online.

Now, we will add reducer to reducers>>index.js

import { CHECKNETSTATUS } from '../constants/ActionTypes'

const netStatus = (state = {connection: false}, action) => {
  switch (action.type) {
      case CHECKNETSTATUS:
        return Object.assign({}, state, {
            connection: action.status,
        });
      default:
        return state
    }
  }

export default combineReducers({ cart,netStatus, products})

In the above, code we are setting the connection property to the current status of the app.

Finally, we will create a Netinfo component where we will check the status of app and dispatch the status to the redux store. We will also add a sliding animation to notify the user. Our Netinfo component code looks like this :

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  NetInfo,
  Animated,
  Dimensions
} from 'react-native';
import { connect } from 'react-redux'
import { updateNetstatus } from '../actions'

const {height, width} = Dimensions.get('window');
const barWidth = width;
const barHeight = 40;
let _this

class Netinfo extends Component {
  constructor(props) {
      super(props);
      this.state = {
        barColor : 'green'
      }
      _this = this
      this.animatedValue = new Animated.Value(-width)
  }

  animate(color) {
    this.setState({ barColor: color})
    this.animatedValue.setValue(-width)
    Animated.timing(
      this.animatedValue,
      {
        toValue: 0,
        duration: 1000
      }
    ).start(() => this.reverseAnimate())
  }
  reverseAnimate(){
    setTimeout(() => {
      Animated.timing(
        this.animatedValue,
        {
          toValue: width,
          duration: 1000
        }
      ).start()
    },1000)
  }
  _handleNetInfo(isConnected){
     isConnected ? _this.animate("green") : _this.animate("red")
     isConnected ? _this.props._Netstatus(true) : _this.props._Netstatus(false)
  }
  componentDidMount() {
      NetInfo.isConnected.addEventListener('change', this._handleNetInfo);
  }
  componentWillUnmount() {
      NetInfo.isConnected.removeEventListener('change', this._handleNetInfo);
  }
  render() {
    const movingPos = this.animatedValue
    return (
      <Animated.View
        style={{
          transform:[{translateX: movingPos}],
          height: barHeight,
          width: barWidth,
          backgroundColor: this.state.barColor}} >
          <Text style={styles.welcome}>
            You are { this.props.status ? 'online' : 'offline' }!
          </Text>
          </Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: "white"
  }
});

const mapStateToProps = (state) => {
    return {
        status: state.netStatus.connection
    };
};
const mapDispatchToProps = dispatch => ({
  _Netstatus: (status) => {
   dispatch(updateNetstatus(status))
}
})
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Netinfo)

In the above code we are using NetInfo.isConnected.addEventListener provided by react native to handle the online status of app. We have attached the event listener to the _handleNetInfo which performs the animation and dispatch the status whenever user goes online or offline.

Now we just add the Netinfo component at the bottom of the main file like this :

import Netinfo from './containers/netinfo.js'

     <View style={styles.container}>
        .
        .
        .
        <Netinfo />
      </View>

You can check how it works in the video below :