import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, NetInfo } from 'react-native';
const NoInternetScreen = () => {
const [isConnected, setIsConnected] = useState(true);
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
setIsConnected(state.isConnected);
});
return () => {
unsubscribe();
};
}, []);
if (!isConnected) {
return (
<View style={styles.container}>
<Text style={styles.text}>No Internet Connection</Text>
</View>
);
}
return null;
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f44336',
},
text: {
color: '#ffffff',
fontSize: 18,
},
});
export default NoInternetScreen;
This component uses the NetInfo API from React Native to listen for changes in the network status. When the device is not connected to the internet, it displays a “No Internet Connection” message. You can use this component in your application to inform users when they lose their internet connection. Please note that you might need to install the @react-native-community/netinfo package if it’s not already installed in your project. You can install it using npm or yarn:
npm install @react-native-community/netinfo
# or
yarn add @react-native-community/netinfo
Remember to import the NoInternetScreen
component in the appropriate place in your application and use it as needed. For example, you could include it in your main App component and it will display the “No Internet Connection” message whenever the device loses its internet connection.
In this example, NoInternetScreen
is imported from the file where you defined it. The NoInternetScreen
component is then used inside the App
component. If the device loses its internet connection, the “No Internet Connection” message will be displayed.
Please replace ./screens/NoInternetScreen
with the actual path where you have the NoInternetScreen
component. Also, remember to place the rest of your app where the comment {/* Rest of your app goes here */}
is. This way, the “No Internet Connection” message will overlay on top of your app whenever there’s no internet connection.
Remember to run your app again after making these changes to see the effect. If you’re using Expo, you can do this by pressing r
in the terminal where you ran expo start
. If you’re not using Expo, you can do this by running react-native run-android
or react-native run-ios
in your terminal, depending on your platform.