Skip to content

Instantly share code, notes, and snippets.

@ronal2do
Forked from sibelius/NetInfo.js
Created August 20, 2017 20:13
Show Gist options
  • Save ronal2do/7c8645c13fb563f9be9ad66e859517cf to your computer and use it in GitHub Desktop.
Save ronal2do/7c8645c13fb563f9be9ad66e859517cf to your computer and use it in GitHub Desktop.
Tiny component that shows an alert bar when there is no internet connection
import React, { Component } from 'react';
import {
View,
Text,
TouchableHighlight,
NetInfo,
} from 'react-native';
export default class ConnectionInfo extends Component {
state = {
connectionInfo: 'none',
show: true,
};
componentDidMount() {
NetInfo.addEventListener('change', this._handleConnectionInfoChange);
NetInfo.fetch().done((connectionInfo) => this.setState({connectionInfo}));
}
_handleConnectionInfoChange = (connectionInfo) => {
let state = {
connectionInfo,
};
if (connectionInfo === 'none') {
if (!this.state.show) {
state = {
...state,
show: true,
};
}
}
this.setState(state);
};
render() {
const { show, connectionInfo } = this.state;
if (!show || connectionInfo !== 'none') {
return null;
}
return (
<View style={{backgroundColor: 'black', padding: 5, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
<Text style={{alignSelf: 'center', color: 'white', textAlign:'center'}}>No Internet Connection</Text>
<TouchableHighlight onPress={() => this.setState({show: false})} style={{alignSelf: 'flex-end'}}>
<Text style={{color: 'white'}}>X</Text>
</TouchableHighlight>
</View>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment