Skip to content

Instantly share code, notes, and snippets.

@SuzaBr
Forked from Chiamaka/OfflineNotice.js
Last active December 1, 2022 07:47
Show Gist options
  • Save SuzaBr/dc6c660ece23867ee936d1427fa7196d to your computer and use it in GitHub Desktop.
Save SuzaBr/dc6c660ece23867ee936d1427fa7196d to your computer and use it in GitHub Desktop.
Rewrite OfflineNotice.js to tsx. NetInfo is deprecated since react-native 0.60. Switch to community version.
/**
* @file Offline notice, responsive to network changes.
*
* @author Chiamaka Nwolisa
* @author SuzaBr
*
* See: https://medium.com/dailyjs/offline-notice-in-react-native-28a8d01e8cd0
* Adapted for community version netinfo, see: https://reactnative.dev/docs/0.60/netinfo.
* Adapted for TypeScript.
*
* BEWARE: This seems to work, still I'm no expert in JavaScript. This file can be bad practice. I don't know.
*/
import React, { PureComponent } from 'react';
import { View, Text, Dimensions, StyleSheet } from 'react-native';
import NetInfo, { NetInfoSubscription } from "@react-native-community/netinfo";
const { width } = Dimensions.get('window');
function MiniOfflineSign() {
return (
<View style={styles.offlineContainer}>
<Text style={styles.offlineText}>No Internet Connection</Text>
</View>
);
}
class OfflineNotice extends PureComponent {
state = {
isConnected: true,
};
private unsubscribe!: NetInfoSubscription; // Need to initialise in didMount
componentDidMount() {
// Subscribe to network chnages
this.unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
this.handleConnectivityChange(state.isConnected);
});
}
componentWillUnmount() {
this.unsubscribe?.(); // Unsubscribe
}
handleConnectivityChange = (isConnected: boolean | null) => {
if (isConnected === null) {
console.error("ApiCall::isConnected is null");
isConnected = false;
}
this.setState({ isConnected });
};
render() {
if (!this.state.isConnected) {
return <MiniOfflineSign />;
}
return null;
}
}
const styles = StyleSheet.create({
offlineContainer: {
backgroundColor: '#b52424',
height: 30,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
width,
position: 'absolute',
top: 30
},
offlineText: { color: '#fff' }
});
export default OfflineNotice;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment