Adding CSS Styling to React Native Webview

Style WebView Inline HTML in React Native

Managed to solve this by using the InjectJavaScript which then allowed me to apply some basic styling, though I had to make a few changes.

// Inject JS for styling
// Original Styling
// lineHeight: 20,
// fontFamily: "Montserrat",
// fontSize: responsiveFontSize(1.6),
const docStyle = `
document.body.style.fontSize = ${responsiveFontSize(4)};
document.body.style.lineHeight = 1.7;
document.body.style.fontFamily = "Montserrat";
`;

<View style={{ flex: 2 }}>
<WebView
source={{ html: canjeableDetail?.description }}
style={{
marginTop: 6,
marginLeft: 16,
marginRight: 16,
}}
injectedJavaScript={docStyle}
/>
</View>;

How do I customize website CSS in a react native webview?

WebView has an "injectedJavaScript" prop available which would allow you to feed it a block of javascript that you could use to manipulate any CSS/HTML on the page.

It's a bit hacky, but I didn't really see an alternative since you're essentially working with an iframe when using a webview.

I'm using this to hide the burger bar in the navbar of a site I reference in a webview in my app:

<WebView
source={{uri: this.state.magicUrl}}
style={{ flex: 1 }}
injectedJavaScript={'function hideHeaderToggle() {var headerToggle = document.getElementsByClassName("navbar-toggle"), i;for (i = 0; i < headerToggle.length; i += 1) {headerToggle[i].style.display = "none";};}; hideHeaderToggle();'}
/>

Entirely possible that there are better alternatives out there, but this certainly would be one option.

React native load css and js Webview

You need to use the injectedJavaScript attribute on the WebView to pass over JS to be executed.

For example:

<WebView html={html}
injectedJavaScript={'function myfunc() { //your JS here };myfunc();'}
javaScriptEnabled={true} />

Inject JavaScript or CSS into React Native WebView before page renders

I couldn't find a way to inject JavaScript or CSS before the page loads.

To workaround the flashing problem, I put another View on top of the WebView while it is still in loading state. The onNavigationStateChanged callback can be used to find out whether the page is loaded. The View I put on top simply shows an ActivityIndicatorIOS.

Use CSS from local file in WebView with React Native and Expo

The easiest way is to wrap your css code into a javascript file:

style.js:

const css = `
<style>
// copy your css file's content here
</style>
`;
export default css;

Then just import style from './style'; and you can simply concat the style to this.fullPost.



Related Topics



Leave a reply



Submit