Browser functionality-related hooks : online/offline

CHIRAG KUMARCHIRAG KUMAR
1 min read

using custom Hooks in React, with Browser functionality we can check whether the Internet connection is Online or Offline

// it reutrn true or false
window.navigator.onLine
import React, { useState,useEffect } from 'react';
import axios from 'axios'

function useIsOnline(){
  const [isOnline, setIsOnline] = useState(window.navigator.onLine)
  useEffect(() => {
    window.addEventListener('online', () => setIsOnline(true));
    window.addEventListener('offline', () => setIsOnline(false));
  }, [])

  return isOnline
}


function App(){
  const isOnline = useIsOnline()
    return (
      <div>
           {isOnline?<div>{todos.map((eachTodo)=><Track  todo= {eachTodo}/>) }</div>
            :<h1>you are offline baby </h1>}
      </div>
    )

}

function Track({todo}){
    return <div>
        {todo.id}<br/>
        {todo.title}<br/>
        {todo.description}<br/>
        {todo.completed}<br/>
    </div>
}


export default App
0
Subscribe to my newsletter

Read articles from CHIRAG KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

CHIRAG KUMAR
CHIRAG KUMAR

Full stack Developer