Created
March 16, 2019 13:10
-
-
Save brandonsueur/5fc242bb1e4e774ff7b048029e10e590 to your computer and use it in GitHub Desktop.
Component React for check is online
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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