Lots of credits to the answers here, but here's a complete example with the useNetInfo
React Hook triggering when the state will change, Alert
to inform the user, and displaying View
with some text to the user.
import { useNetInfo, NetInfoState } from "@react-native-community/netinfo";
import {
Alert,
StyleSheet,
Text,
View,
} from "react-native";
...
const internetState: NetInfoState = useNetInfo();
...
useEffect(() => {
if (internetState.isConnected === false) {
Alert.alert(
"No Internet! ❌",
"Sorry, we need an Internet connection for MY_APP to run correctly.",
[{ text: "Okay" }]
);
}
}, [internetState.isConnected]);
...
if (internetState.isConnected === false) {
return (
<View style={styles.centered}>
<Text style={styles.title}>
Please turn on the Internet to use MY_APP.
</Text>
</View>
);
}
...
const styles = StyleSheet.create({
centered: {
alignItems: "center",
flex: 1,
justifyContent: "center",
},
title: {
fontSize: 20,
fontWeight: "bold",
textAlign: "center",
},
});
PS. I couldn't succeed to include it in App.tsx
or navigation/index.tsx
to avoid code duplication. Next try, I've included the logic in every screen
. For the App.tsx
or navigation/index.tsx
case, whenever internet was back, the user was redirected to the starting screen
of the app, which is not what I wanted. I wanted, when the internet is back, to be back on the screen where the user ended. With the logic in multiple screens, multiple alerts
are being fired :( Finally, I've included the Alert
-related logic in App.tsx
, whereas the View
with information about no internet in each screen
. The Alert
pops up only once, but it'd be the best to avoid code duplication, too, regarding the View
. Please feel free to post an update, if you know how to do it from 1 location of the codebase in the application. It'd be so much appreciated!