Hi Guys, nowadays the internet is so fast but sometimes we still need it working offline because we can’t imagine when the internet is too slow, struggling or losing connection completely. Then if we can keep our app or game working smoothly and consistently as much as possible will be a better experience for users and good feedback too.
I’ve used RN 0.61.5 for this but don’t use lower than RN 0.60.0 and I’ve mainly used npm than yarn, who using yarn please adapt to your command. I’ve created a new project with a command line from Terminal like below.
npx react-native init HelloWorld --version 0.61.5
After that locate into the HelloWorld folder and use the below command line.
npm install @react-native-community/netinfo
Modified HelloWorld
index.js
Find HelloWorld/index.js open with the Text editor looking at line import App from './App'; and change it to import App from './src/main/App'; then save file.
npx react-native init HelloWorld --version 0.61.5
After that locate into the HelloWorld folder and use the below command line.
npm install @react-native-community/netinfo
index.js
Find HelloWorld/index.js open with the Text editor looking at line import App from './App'; and change it to import App from './src/main/App'; then save file.
From root project create folder named ‘src’ and under src folder create 2 folders named ‘components’ and ‘main’, then create new file under ‘HelloWorld/src/components’ named ‘OfflineNotice.js’ after that under ‘ HelloWorld/src/main’ create new file named ‘App.js’ and ‘MainApplication.js’
New HelloWorld Structure
Open ‘HelloWorld/src/main/App.js’ with TextEditor and then place this code and save.
Hint: This is the top most of our application that is called from index.js, i’ve decided to keep original App.js from initializing the project and change to my own App.js, this file will render MainApplication.js here.
MainApplication.js
Open ‘HelloWorld/src/main/MainApplication.js’ with TextEditor and then place this code and save.
Import OfflineNotice component will be used here, here at MainApplication state we’ve initial state isConnected is false.
i’ve created an updateConnection function for retrieve update isConnected into here for update MainApplication text HelloWorld : ONLINE or OFFLINE, you may not want this in your app. Under render I've used OfflineNotice here and bind function updateConnection for trigger update isConnected back. If you don’t want updateConnection just leave only <OfflineNotice />
OfflineNotice.js
Open ‘HelloWorld/src/components/OfflineNotice.js’ with TextEditor and place this code and save.
Hint: The last one is OfflineNotice component, this is mainly status update network connection and update display top bar overlay on screen both ‘Offline Mode’ always and ‘Online Mode’ for 3 sec. then disappearance.
This component using @react-native-community/netinfo dependency for listen status of network connection, at the initialize of OfflineNotice i’ve set isConnected is false, onlineTrigger is false, animateTrigger is false, statusBarHeight is zero (this using for iOS notch screen), showOnline is 3000 (3 sec. For show status Online Mode), timer and unsubscribe is null.
Under componentDidMount I’ve use connector props through OfflineNotice component in MainApplication for sending update isConnected back to updateConnection function in MainApplication, StatusBar height will update here too, then i’ve set network listener here, after that i can update all state from constructor to handling callback and trigger animate when status change between online and offline.
Under componentWillUnmount I’ve used unsubscribe and clear timer here to avoid memory leak issues in that case trigger.
In render just a simple check isConnected and animateTrigger then return sub view OfflineMode and OnlineMode for OnlineMode i’ve shown only 3 sec. Then return blank view (you may have use return null)
For iOS
Locate into the HelloWorld/ios and then use the command line pod init if your folder does not have a Pod file here, then pod install and wait until finished then open HelloWorld.xcworkspace with Xcode, choose simulator and play, see what happens on screen and top bar.
Recommend Testing on iOS Device
Xcode : Error
Could not launch “HelloWorld”
Back to Xcode click OK and the play again.
Result (iOS Device)
Online Mode will show 3 sec. then disappear, try turning off the internet on the iPhone then the top bar will change to Offline Mode and the main screen will update text as HelloWorld : OFFLINE too.
Thank you so much for visit this blog. See U next thread. :)
No Like, No Thumbs Up, No Bell, Please support me by click ads, thank you...
New HelloWorld Structure
HelloWorld
|--- __tests__ |--- android
|--- ios
|--- node_modules
|--- src | |--- components
| | |--- OfflineNotice.js | |--- main | |--- App.js
| |--- MainApplication.js
|--- index.js
Open ‘HelloWorld/src/main/App.js’ with TextEditor and then place this code and save.
import React, { Component } from "react";
import MainApplication from "./MainApplication";
class App extends Component {
render() {
return (
<MainApplication />
);
}
}
export default App;
Hint: This is the top most of our application that is called from index.js, i’ve decided to keep original App.js from initializing the project and change to my own App.js, this file will render MainApplication.js here.
MainApplication.js
Open ‘HelloWorld/src/main/MainApplication.js’ with TextEditor and then place this code and save.
import React, { Component } from 'react';
import { View, StatusBar, Text, StyleSheet } from 'react-native';
import OfflineNotice from "../components/OfflineNotice";
class MainApplication extends Component {
constructor(props) {
super(props);
this.state = {
isConnected: false
};
}
//This function bind to OfflineNotice to retrieve connection status
updateConnection(result) {
this.setState({ isConnected: result });
}
render() {
return (
<View style={styles.container}>
<StatusBar barStyle="default" />
<View style={styles.textContainer}>
<Text style={styles.statusText}>
Hello World : {this.state.isConnected ? 'ONLINE' : 'OFFLINE'}
</Text>
</View>
<OfflineNotice connector={this.updateConnection.bind(this)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#ABEBC6',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
width: '100%',
flex: 1,
},
textContainer: {
borderColor: '#229954',
borderTopWidth: 1,
borderBottomWidth: 1,
backgroundColor: '#fff',
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center',
height: 28,
flex: 1,
},
statusText: {
color: '#229954',
height: 80,
fontWeight: '700',
fontSize: 18,
},
});
export default MainApplication;
Import OfflineNotice component will be used here, here at MainApplication state we’ve initial state isConnected is false.
i’ve created an updateConnection function for retrieve update isConnected into here for update MainApplication text HelloWorld : ONLINE or OFFLINE, you may not want this in your app. Under render I've used OfflineNotice here and bind function updateConnection for trigger update isConnected back. If you don’t want updateConnection just leave only <OfflineNotice />
OfflineNotice.js
Open ‘HelloWorld/src/components/OfflineNotice.js’ with TextEditor and place this code and save.
import React, { Component } from 'react';
import { View, NativeModules, Text, StyleSheet } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
const { StatusBarManager } = NativeModules
const OfflineMode = ({ iosBar }) => {
return (
<View style={[styles.offlineContainer, { top: iosBar }]}>
<Text style={styles.offlineText}>Offline Mode</Text>
</View>
);
}
const OnlineMode = ({ iosBar }) => {
return (
<View style={[styles.onlineContainer, { top: iosBar }]}>
<Text style={styles.onlineText}>Online Mode</Text>
</View>
);
}
class OfflineNotice extends Component {
constructor(props) {
super(props);
this.state = {
isConnected: true,
onlineTrigger: false,
animateTrigger: false,
statusBarHeight: 0,
showOnline: 3000
};
this.timer = null;
this.unsubscribe = null;
}
componentDidMount() {
const { connector } = this.props;
if (Platform.OS === 'ios') {
StatusBarManager.getHeight(response =>
this.setState({ statusBarHeight: response.height })
)
}
this.unsubscribe = NetInfo.addEventListener(state => {
this.setState({ isConnected: state.isConnected });
if (connector !== undefined && connector !== null) {
connector(state.isConnected);
}
if (state.isConnected) {
if (this.state.onlineTrigger == false) {
this.setState({ animateTrigger: true });
this.setState({ onlineTrigger: true });
this.timer = setTimeout(() =>
this.setState({ animateTrigger: false }),
this.state.showOnline);
}
} else {
this.setState({ onlineTrigger: false });
}
});
}
clearTimer() {
if (this.timer !== undefined && this.timer !== null) {
clearTimeout(this.timer);
}
}
componentWillUnmount() {
this.unsubscribe();
this.clearTimer();
}
handleConnectivityChange = isConnected => {
this.setState({ isConnected });
};
render() {
if (!this.state.isConnected) {
return <OfflineMode iosBar={this.state.statusBarHeight} />;
} else {
if (this.state.animateTrigger) {
return <OnlineMode iosBar={this.state.statusBarHeight} />;
} else {
return (<View></View>);
}
}
}
}
const styles = StyleSheet.create({
offlineContainer: {
backgroundColor: '#ff3333',
height: 30,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
position: 'absolute',
top: 0,
width: '100%',
},
offlineText: {
color: '#fff'
},
onlineContainer: {
backgroundColor: '#4b810b',
height: 30,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
position: 'absolute',
top: 0,
width: '100%',
},
onlineText: {
color: '#fff'
},
});
export default OfflineNotice;
Hint: The last one is OfflineNotice component, this is mainly status update network connection and update display top bar overlay on screen both ‘Offline Mode’ always and ‘Online Mode’ for 3 sec. then disappearance.
This component using @react-native-community/netinfo dependency for listen status of network connection, at the initialize of OfflineNotice i’ve set isConnected is false, onlineTrigger is false, animateTrigger is false, statusBarHeight is zero (this using for iOS notch screen), showOnline is 3000 (3 sec. For show status Online Mode), timer and unsubscribe is null.
Under componentDidMount I’ve use connector props through OfflineNotice component in MainApplication for sending update isConnected back to updateConnection function in MainApplication, StatusBar height will update here too, then i’ve set network listener here, after that i can update all state from constructor to handling callback and trigger animate when status change between online and offline.
Under componentWillUnmount I’ve used unsubscribe and clear timer here to avoid memory leak issues in that case trigger.
In render just a simple check isConnected and animateTrigger then return sub view OfflineMode and OnlineMode for OnlineMode i’ve shown only 3 sec. Then return blank view (you may have use return null)
For iOS
Locate into the HelloWorld/ios and then use the command line pod init if your folder does not have a Pod file here, then pod install and wait until finished then open HelloWorld.xcworkspace with Xcode, choose simulator and play, see what happens on screen and top bar.
Recommend Testing on iOS Device
Xcode : Error
Could not launch “HelloWorld”
Back to Xcode click OK and the play again.
Result (iOS Device)
Thank you so much for visit this blog. See U next thread. :)
No Like, No Thumbs Up, No Bell, Please support me by click ads, thank you...






Comments
Post a Comment