Last active
October 19, 2018 23:34
-
-
Save barnslig/bc4d9b2d9a5368269c03f1d9b653f89b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 React from 'react'; | |
import PropTypes from 'prop-types'; | |
/** | |
* React component that keeps you up to date about navigator.onLine | |
* | |
* @example | |
* <Online> | |
* {isOnline => (isOnline ? <span>online!</span> : <span>offline!</span>)} | |
* </Online> | |
* | |
* @see [Online and offline events]{@link https://developer.mozilla.org/en/Online_and_offline_events} | |
* @author [Leonard Techel]{@link https://github.com/barnslig} | |
* @version 0.0.2 | |
*/ | |
class Online extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
/** | |
* Whether navigator.onLine | |
* | |
* @type {bool} | |
*/ | |
isOnline: navigator.onLine, | |
}; | |
this.onOffline = this.onOffline.bind(this); | |
this.onOnline = this.onOnline.bind(this); | |
} | |
componentDidMount() { | |
window.addEventListener('online', this.onOnline); | |
window.addEventListener('offline', this.onOffline); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('online', this.onOnline); | |
window.removeEventListener('offline', this.onOffline); | |
} | |
async onOffline() { | |
const { onOffline } = this.props; | |
await onOffline(); | |
this.setState({ isOnline: false }); | |
} | |
async onOnline() { | |
const { onOnline } = this.props; | |
await onOnline(); | |
this.setState({ isOnline: true }); | |
} | |
render() { | |
const { children } = this.props; | |
const { isOnline } = this.state; | |
return children(isOnline); | |
} | |
} | |
Online.propTypes = { | |
/** | |
* Single-Parameter child function whether the navigator is online | |
* | |
* @type {function} | |
*/ | |
children: PropTypes.func.isRequired, | |
/** | |
* Optional callback for when the navigator gets offline | |
* | |
* When returning a Promise, the state is not transformed until it is | |
* resolved. | |
* | |
* @type {function} | |
*/ | |
onOffline: PropTypes.func, | |
/** | |
* Optional callback for when the navigator gets online | |
* | |
* When returning a Promise, the state is not transformed until it is | |
* resolved. | |
* | |
* @type {function} | |
*/ | |
onOnline: PropTypes.func, | |
}; | |
Online.defaultProps = { | |
onOffline: () => {}, | |
onOnline: () => {}, | |
}; | |
export default Online; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment