react-native-modern-elements
Version:
A modern, customizable UI component library for React Native
82 lines (81 loc) • 3.05 kB
JavaScript
import NetInfo from "@react-native-community/netinfo";
import React, { memo, useEffect, useRef, useState } from "react";
import { StyleSheet, Text, } from "react-native";
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
const InternetStatusToast = ({ backOnlineText = "Back online", noInternetText = "No Internet", noInternetBg = "red", backOnlineBg = "green", TextStyles, ViewStyles, }) => {
const [message, setMessage] = useState("");
const [show, setShow] = useState(false);
const [isConnected, setIsConnected] = useState(true);
const prevConnection = useRef(null);
const timeoutRef = React.useRef(null);
useEffect(() => {
const unsubscribe = NetInfo.addEventListener((state) => {
var _a;
const currentConnection = (_a = state.isConnected) !== null && _a !== void 0 ? _a : false;
// First render
if (prevConnection.current === null) {
prevConnection.current = currentConnection;
setIsConnected(currentConnection);
if (!currentConnection) {
setMessage(noInternetText);
setShow(true);
}
return;
}
// Disconnected
if (!currentConnection && prevConnection.current) {
setMessage(noInternetText);
setShow(true);
}
// Reconnected
if (currentConnection && !prevConnection.current) {
setMessage(backOnlineText);
setShow(true);
// Auto-hide
if (timeoutRef.current)
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => setShow(false), 2000);
}
prevConnection.current = currentConnection;
setIsConnected(currentConnection);
});
return () => {
unsubscribe();
if (timeoutRef.current)
clearTimeout(timeoutRef.current);
};
}, [backOnlineText, noInternetText]);
if (!show)
return null;
return (React.createElement(Animated.View, { entering: FadeInDown.duration(300)
.springify()
.damping(8)
.stiffness(80)
.mass(0.8), exiting: FadeOut.duration(300)
.springify()
.damping(8)
.stiffness(80)
.mass(0.8), style: [
styles.container,
ViewStyles,
{ backgroundColor: isConnected ? backOnlineBg : noInternetBg },
] },
React.createElement(Text, { style: [styles.text, TextStyles] }, message)));
};
const styles = StyleSheet.create({
container: {
position: "absolute",
bottom: 0,
left: 0,
right: 0,
zIndex: 9999,
height: 28,
justifyContent: "center",
alignItems: "center",
},
text: {
color: "white",
fontWeight: "500",
},
});
export default memo(InternetStatusToast);