Sometimes you need to show some HTML in a webview in Expo, that comes bundled with the app itself. I could not find a nice clean example with the following requirements:
- Typescript
- Expo (currently at SKD version 40)
- ES6 imports
So here is what the App.tsx
looks like in a minimal example:
import React from "react";
import { StyleSheet, View } from "react-native";
import WebView from "react-native-webview";
import html from "./myhtml"
export default function App() {
return (
<View style={styles.container}>
<WebView
source={{ html }} // shorthand for "html: html"
style={styles.webview}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
webview: {
margin: 30,
backgroundColor:"#eee"
},
});
We are importing the html and simply passing it in as html source into the webviews html property. The magic / hack however happens in a file called myhtml.ts
that in this simple example lies next to the App.tsx file and looks like this:
const myhtml = `
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body style="background-color:'red'">
Hello, I am an imported HTML page!
</body>
</html>
`
export default myhtml
This is also very straight forward. We are simply declaring the HTML as a string (in template literal format, so at least the formatting is readable) and exporting it. Of course that could also happen in the view where you have the webview but this way each file has a specific purpose.
There is the caveat, that there's no syntax highlighting inside the template literal. But this can be acceptable in some cases, if you just have a pre-built HTML file and want to quickly display it, so pasting it into a source string like this is a reasonable approach.
We found a lot of different (and sometimes complicated) answers to this question when it sounded like all that was needed was something really simple like this.
If you want to see it in action check out: https://github.com/qubidu/expo-include-local-html-in-webview/