All writing
July 16, 2021 · 1 min read
Offline screen in React Native with NetInfo
Detect connectivity changes in React Native and render an offline screen using @react-native-community/netinfo — six small steps.
#react-native#android
So you want to check internet connection and show an offline screen if you are disconnected?
Steps:
- Install the netinfo package:
npm install --save @react-native-community/netinfo- Import and declare:
let NetInfoSubscription = null- Initialize state:
const [connectionStatus, setConnectionStatus] = useState(false)- Handle connection changes:
const handleConnectionChange = (state) => {
setConnectionStatus(state.isConnected)
}- Inside
useEffect, subscribe:
NetInfoSubscription = NetInfo.addEventListener(handleConnectionChange)
return () => {
NetInfoSubscription
}- Render conditionally:
connectionStatus ? <MainContent /> : <OfflineScreen />That's it.