2 Minutes Read
By @akash_dathan
By @akash_dathan
Offline Notice Component In Ionic React
Let’s see how we can build an offline notice component for Ionic using React which displays a component when the device is offline

We will be using the capacitor network plugin to pull the native network statuses from the device. Use the following commands to install the module
npm install @capacitor/network
npx cap sync
Once the module is installed, let’s start building the component as follows
import React from 'react';
import { IonChip } from '@ionic/react';
import { Network } from '@capacitor/network';
export class NoInternet extends React.Component {
constructor(props: Props) {
super(props);
this.state = { connected: true };
this.getConnection();
}
async getConnection() {
const status = await Network.getStatus();
if(!status.connected) {
this.setState({ connected: status.connected });
}
Network.addListener('networkStatusChange', ({ connected }) => {
this.setState({ connected });
});
}
render() {
if (this.state.connected) return;
return (
<IonChip className="NoInternet" color="danger">
No Internet
</IonChip>
);
}
}
- as per the code above,
getConnection
is called in the constructor, so that its initialised Network.addListener
will keep track of the network status change, and update the states accordingly.
This component can be used in the code without any conditions, since it returns
undefined
if the networj status is online. Following is an example
of how you can use it in the code.
render() {
return (
<IonPage>
...
<IonContent>
<IonHeader>
<IonToolbar>
<IonTitle>
Search Bar
</IonTitle>
</IonToolbar>
</IonHeader>
<IonSearchbar/>
// Can be used like this directly
<NoInternet/>
...
</IonContent>
</IonPage>
);
}
That’s all folks, happy hacking 🙌