Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use React's Context API in React Native (0.59.0) to have network connectivity status globally available. Gist for Medium article: https://medium.com/@jvandenaardweg/easily-manage-connection-status-updates-in-react-native-28c9b4b0647f
import React from 'react';
import { NetworkProvider } from './NetworkProvider';
import { ExampleComponent } from './ExampleComponent';
export default class App extends React.PureComponent {
render() {
return (
<NetworkProvider>
<ExampleComponent />
</NetworkProvider>
);
}
}
import React from 'react';
import { View, Text } from 'react-native';
import { NetworkContext } from './NetworkProvider';
export class ExampleComponent extends React.PureComponent {
static contextType = NetworkContext;
render() {
return (
<View>
<Text>You are now {this.context.isConnected ? 'online' : 'offline'}</Text>
</View>
);
}
}
import { AppRegistry } from 'react-native';
import App from './App'
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App);
import React from 'react';
import NetInfo from '@react-native-community/netinfo';
export const NetworkContext = React.createContext({ isConnected: true });
export class NetworkProvider extends React.PureComponent {
state = {
isConnected: true
};
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
}
handleConnectivityChange = isConnected => this.setState({ isConnected });
render() {
return (
<NetworkContext.Provider value={this.state}>
{this.props.children}
</NetworkContext.Provider>
);
}
}
@vfa-namth

This comment has been minimized.

Copy link

vfa-namth commented Dec 5, 2019

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.