I want a WebView component to display both when online and offline. When online, I want it to use the url I have provided. I want the locally saved/Cached so it can also be displayed when offline. Here’s a code example:
`import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import WebView from 'react-native-webview';
function App() {
return (
<WebView style={styles.container}
source={{ uri: 'https://wikipedia.org' }} //a random example
/>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
})
export default App;`
I tried using different dependencies but failed. I’m pretty new to react-native, please don’t make it too complex when answering.
2
Answers
If I got it right you want to conditionally chose between an external URL and a local file, depending if you’re online or not.
As described in this answer to a previous question you can import netInfo from react-native-community and check through
netInfo.isConnected
.Since you’re not using
react-native-community
you can insert netinfo separately into your project:or
Then you can change the source parameter of your WebView component as described in this answer to a previous question.
So the code goes like the following:
If you need help undersing the line
source={ isConnected ? { uri: 'https://wikipedia.org' } : localSource }
you can read more about Conditional Operator here.I think you are talking about caching right?
But, you don’t need that because the default is
true
https://github.com/react-native-webview/react-native-webview/blob/master/docs/Reference.md#cacheenabled
First, you have to understand…
BTW: I don’t think you need to show the diff URLs between online/offline, because the WebView will show the message anyway.
But you can play around
source
(which is another question)