Skip to content

Instantly share code, notes, and snippets.

@brandonsueur
Created March 16, 2019 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonsueur/5fc242bb1e4e774ff7b048029e10e590 to your computer and use it in GitHub Desktop.
Save brandonsueur/5fc242bb1e4e774ff7b048029e10e590 to your computer and use it in GitHub Desktop.
Component React for check is online
import { Component } from 'react';
import PropTypes from 'prop-types';
const isNavigatorOnline = () => navigator.onLine || false;
export default class IsOnline extends Component {
static propTypes = {
OnlineComponent: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
OfflineComponent: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
onChange: PropTypes.func,
};
static defaultProps = {
OnlineComponent: null,
OfflineComponent: null,
onChange: null,
};
state = {
events: ['online', 'offline', 'load'],
isOnline: isNavigatorOnline(),
}
componentDidMount = () => {
this.state.events.forEach(event => window.addEventListener(event, this.updateState));
}
componentWillUnmount = () => {
this.state.events.forEach(event => window.removeEventListener(event, this.updateState));
}
updateState = () => {
const isOnline = isNavigatorOnline();
this.setState({ isOnline });
if (this.props.onChange) this.props.onChange(isOnline);
}
render() {
const { OnlineComponent, OfflineComponent } = this.props;
return this.state.isOnline ? OnlineComponent : OfflineComponent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment