React useNavigatorOnLine Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to use the useNavigatorOnLine hook in React to check whether a client is online or offline. We will create a function to get the online status of the client using the Navigator.onLine web API, use the useState() hook to create an appropriate state variable, and add listeners for appropriate events using the useEffect() hook to update the state and clean up those listeners when unmounting. Finally, we will return the online status state variable to display a message based on the current online status.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38398{{"`React useNavigatorOnLine Hook`"}} react/event_handling -.-> lab-38398{{"`React useNavigatorOnLine Hook`"}} react/conditional_render -.-> lab-38398{{"`React useNavigatorOnLine Hook`"}} react/hooks -.-> lab-38398{{"`React useNavigatorOnLine Hook`"}} react/use_state_reducer -.-> lab-38398{{"`React useNavigatorOnLine Hook`"}} end

React useNavigatorOnLine Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To check if the client is online or offline, you can create a getOnLineStatus function that utilizes the Navigator.onLine web API. Then, to implement this functionality in a React component, you can use the useNavigatorOnLine custom hook. This hook creates a state variable called status using the useState() hook and sets it to the value returned by getOnLineStatus(). The useEffect() hook is used to add event listeners for when the online/offline status changes, update the status state variable accordingly, and clean up those listeners when the component unmounts. Finally, the isOnline variable returned by useNavigatorOnLine() can be used to render a message indicating whether the client is online or offline.

const getOnLineStatus = () =>
  typeof navigator !== "undefined" && typeof navigator.onLine === "boolean"
    ? navigator.onLine
    : true;

const useNavigatorOnLine = () => {
  const [status, setStatus] = React.useState(getOnLineStatus());

  const setOnline = () => setStatus(true);
  const setOffline = () => setStatus(false);

  React.useEffect(() => {
    window.addEventListener("online", setOnline);
    window.addEventListener("offline", setOffline);

    return () => {
      window.removeEventListener("online", setOnline);
      window.removeEventListener("offline", setOffline);
    };
  }, []);

  return status;
};

const StatusIndicator = () => {
  const isOnline = useNavigatorOnLine();

  return <span>You are {isOnline ? "online" : "offline"}.</span>;
};

ReactDOM.createRoot(document.getElementById("root")).render(
  <StatusIndicator />
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useNavigatorOnLine Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like