1.0.2 • Published 3 years ago

react-network-status v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

ReactNetworkStatus

  • This is a React Js library that provides network status (online/offline) with polling.

Installation

npm i react-network-status or yarn add react-network-status

Usage

useNetworkStatus Hook for functional Components in React

Hook that updates component with the network status offline/online state.

This gives user a flexibility to programmatically render UI components.

import { useNetworkStatus } from "react-network-status";

const App = () => {
  const [networkStatus, setNetworkStatus] = useState(true);
  const config = {
    timeout: 5000,
    interval: 1000,
  };

  useNetworkStatus((networkStatusUpdate) => {
    setNetworkStatus(networkStatusUpdate);
  }, config);

  return <div>You are: {networkStatus ? "online" : "offline"}</div>;
};

Components

NetworkDetector - Component that can be used in State based Components.

It has no UI but just accepts config and onChange event.

import { NetworkDetector } from "react-network-status";

class App extends Component {
  state = {
    networkStatus: true,
  };

  config = {
    timeout: 5000,
    interval: 1000,
  };

  onNetworkStatusChange = (networkStatus: boolean) => {
    this.setState({ networkStatus });
  };

  render() {
    const { networkStatus } = this.state;

    return (
      <div>
        You are: {networkStatus ? "online" : "offline"}
        <NetworkDetector
          config={this.config}
          onChange={this.onNetworkStatusChange}
        />
      </div>
    );
  }
}

Props

<NetworkDetector/>, and useNetworkStatus accept the following props:

const config = {
  url: // YOUR_POLLING URL,
  interval: // YOUR POLLING INTERVAL,
  timeout: // YOUR POLLING TIMEOUT
};

onChange: Event that provides status (true or false) as online value of the network.

PropTypeDescriptionDefault
configObj or BoolConfig for polling fallback 1see below
config.enabledBooleanForce polling on or offDepends on the browser 1
config.urlStringURL to pool for connection status"https://ipv4.icanhazip.com"
config.intervalNumberHow often (in ms) to poll5000
config.timeoutNumberHow long (in ms) before timeout5000
onChangeFunctionCalled when connection changesnone

1 Polling is only used as a fallback for browsers that don't support the "online" event. Currently these are Chrome on Windows, Firefox on Windows, and Chrome on Linux.

2 <NetworkDetector/> will not render children.

Services

Author

  • Name: Tofiq Quadri
  • Email: tofiqquadri@developershive.com
  • This package is maintained by tofiqquadri.