Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. import { Component } from 'react';
  2. import PropTypes from 'prop-types';
  3.  
  4. const isNavigatorOnline = () => navigator.onLine || false;
  5.  
  6. export default class IsOnline extends Component {
  7. static propTypes = {
  8. OnlineComponent: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  9. OfflineComponent: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  10. onChange: PropTypes.func,
  11. };
  12.  
  13. static defaultProps = {
  14. OnlineComponent: null,
  15. OfflineComponent: null,
  16. onChange: null,
  17. };
  18.  
  19. state = {
  20. events: ['online', 'offline', 'load'],
  21. isOnline: isNavigatorOnline(),
  22. }
  23.  
  24. componentDidMount = () => {
  25. this.state.events.forEach(event => window.addEventListener(event, this.updateState));
  26. }
  27.  
  28. componentWillUnmount = () => {
  29. this.state.events.forEach(event => window.removeEventListener(event, this.updateState));
  30. }
  31.  
  32. updateState = () => {
  33. const isOnline = isNavigatorOnline();
  34. this.setState({ isOnline });
  35. if (this.props.onChange) this.props.onChange(isOnline);
  36. }
  37.  
  38. render() {
  39. const { OnlineComponent, OfflineComponent } = this.props;
  40.  
  41. return this.state.isOnline ? OnlineComponent : OfflineComponent;
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement