Showing an offline screen for your React-Native app using NetInfo package.

So you want to check internet connection and show an offline screen if you are disconnected?

Here are simple steps to create one:

1) Install netinfo package from npm:
npm install --save @react-native-community/netinfo

2) Import it in your js file wherever you want it to be, declare a variable and set it's value to null:
let NetInfoSubscription = null;

3) Initialize a state and set the default value to false:
const [connectionStatus, setConnectionStatus] = useState(false);

4) Create a function that changes the value of the connectionStatus based on if the internet is connected or not:

const handleConnectionChange = (state) => {
    setConnectionStatus(state.isConnected);
  };

5) Inside useEffect hook reassign the value of NetInfoSubscription and add this piece of code:

NetInfoSubscription = NetInfo.addEventListener(handleConnectionChange);
    return () => {
      NetInfoSubscription;
    };

6) Now just use a ternary operator to show the main contents if the connection is there or show the offline screen if the connection is disconnected.
example:

connectionStatus ? <MainContent /> : <OfflineScreen />

That is it now if the internet is disconnected offline screen will be rendered.

Let me know if you have some questions or want to see how I created my Offline Screen :)

17