How to check for an internet connection in an Expo React Native app?
It's really hard to define if a device has internet or not stackoverflow.com/a/189443/7602110, just by having failed XHR requests you can say that you have internet, but isn't that reliable. You would like to check with some reliables websites like google.com, I have come with a work-around but I don't actually recommend it, is up to you.
You can use the Linking.canOpenUrl()
method from React Native itself, which will return a Promise object. When it is determined whether or not the given URL can be handled, the promise is resolved and the first parameter is whether or not it can be opened.
Then add a request and if the response status it's 200
you should have internet.
import React, { Component } from 'react';
import { Button, Text, View, StyleSheet, Linking } from 'react-native';
export default class App extends Component {
state = {
connection: false,
url: 'https://google.com',
};
checkInternt = () => {
Linking.canOpenURL(this.state.url).then(connection => {
if (!connection) {
this.setState({ connection: false });
} else {
fetch(this.state.url).then(res =>
this.setState({ connection: res.status !== 200 ? false : true })
);
}
});
};
componentDidMount() {
this.checkInternt();
}
handlePress = () => {
this.setState({
url:
this.state.url === 'https://google.com'
? 'http://someweirdurlthatdoesntwork.com'
: 'https://google.com',
});
this.checkInternt();
};
render() {
return (
<View style={styles.container}>
<Text>
Connection:
<Text style={{ color: this.state.connection ? 'green' : 'red' }}>
{` ${this.state.connection}`}
</Text>
</Text>
<Text>{this.state.url.replace(/\https?:\/\//g, '')}</Text>
<Button onPress={this.handlePress} title="Change server url" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
});
Check the snack: snack.expo.io/@abranhe/check-internet
Expo SDK 34 has already included NetInfo API
.
You can check their documentation for SDK 34 here https://docs.expo.io/versions/v34.0.0/sdk/netinfo
Here is the link for documentation for latest version
Use NetInfo
of react-native
.
Yes, it is deprecated because they are planning on removing it in the next version of react-native
in favor of the community version. However, it is completely functional and can still be used for now, just make sure to check for breaking changes when the next versions of Expo SDK
are released.
It is likely that Expo will bring it into their managed workflow when react-native
removes it, or provide an alternative that won't require ejecting from Expo.