Skip to content

Instantly share code, notes, and snippets.

@Chiamaka
Last active December 1, 2022 07:50
Show Gist options
  • Save Chiamaka/c28010389c830ac675643c7291c3a7df to your computer and use it in GitHub Desktop.
Save Chiamaka/c28010389c830ac675643c7291c3a7df to your computer and use it in GitHub Desktop.
import React, { PureComponent } from 'react';
import { View, Text, NetInfo, Dimensions, StyleSheet } from 'react-native';
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
};
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
}
handleConnectivityChange = isConnected => {
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;
@rafaelmaza
Copy link

I've updated componentDidMount to read the initial connection state, so the message is displayed when the app launches if the user is offline:

  componentDidMount () {
    NetInfo.isConnected.fetch().then(this.handleConnectivityChange)

    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange)
  }

also, if the screen rotates, width doesn't get updated... there's a workaround by setting:

const styles = StyleSheet.create({
  offlineContainer: {
    // don't set width
    left: 0,
    right: 0
    // ...
  },
//...

another smaller comment is that both if/else cases in handleConnectivityChange do the same - could be replaced with:

  handleConnectivityChange = isConnected => {
    this.setState({ isConnected })
  }

@SuzaBr
Copy link

SuzaBr commented Dec 1, 2022

Tried to make this work in Expo App with typescript.
Think it works now (2022-11).Got a fork.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment