DEV Community 👩‍💻👨‍💻

SagarTrimukhe
SagarTrimukhe

Posted on

No Internet Connection wrapper for React apps

Imagine,
We have a web application that heavily depends on the backend server for information (eg. records in a table) and that information needs to be constantly updated. We might think to use some polling mechanism.

But if the data received from the server is directly stored in a React state variable and if the user loses the internet connection then there are chances of updating the state with empty data.

So, instead of showing empty data, we can show a message, something like "No internet connection."

How can we do that?

We can write a wrapper component and wrap the entry-level component. So whenever the internet connection is lost, a custom page/message can be shown.

Here I have used the navigator.onLine API to get the network status.

enough story, show me the code :)

Main component

import './App.css';
import NoInternetConnection from './NoInternetConnection'

function App() {
  return (
    <div className="App">
        <NoInternetConnection>
        <h1>My first post on DEV!!</h1>
        </NoInternetConnection>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Wrapper component

import React, {useState, useEffect} from 'react';

const NoInternetConnection = (props) => {
    // state variable holds the state of the internet connection
    const [isOnline, setOnline] = useState(true);

    // On initization set the isOnline state.
    useEffect(()=>{
        setOnline(navigator.onLine)
    },[])

    // event listeners to update the state 
    window.addEventListener('online', () => {
        setOnline(true)
    });

    window.addEventListener('offline', () => {
        setOnline(false)
    });

    // if user is online, return the child component else return a custom component
    if(isOnline){
    return(
        props.children
    )
    } else {
        return(<h1>No Interner Connection. Please try again later.</h1>)
    }
}

export default NoInternetConnection;
Enter fullscreen mode Exit fullscreen mode

Here is the demo.

ezgif.com-gif-maker

That's it. By the way, this is my first post on DEV (damn! on the internet :)). Feedback is appreciated.

Top comments (1)

Collapse
tmashwani profile image
tmashwani

if props.children is any form or any page when get establish our internet connection we want the previous sate of props.children how will we tackle this.

🌚 Life is too short to browse without dark mode