In the previous tutorial, we learn how to create React native app from an already-existing website using webview.
When I created an app from a website, the major challenge I faced is to apply the CSS.
I wanted to style some of the UI components. But there is no direct way. After. doing a lot of research and trying different things, I finally cracked it.
The first question is, can we add CSS to the React-Native…
Yes, you can.
CSS styles to a WebView component in a React Native app can be applied using the injectedJavaScript
prop along with the source prop.
Let’s take the same example from our previous tutorial and will add the necessary code.
import * as React from "react"; import { WebView } from "react-native-webview"; export default class App extends React.Component { render() { // newly added code const injectedJavaScript = ` const style = document.createElement('style'); style.innerHTML = 'body { background-color: red; }'; document.head.appendChild(style); `; return ( <WebView source={{ uri: 'https://example.com/' }} style={{ marginTop: 20 }} //newly added code injectedJavaScript={injectedJavaScript} /> ); } }
Code Explanation
You can modify the code inside the injectedJavaScript
variable to apply CSS to any other UI component like buttons, tables, headings, etc…
In the above example, we have changed the background color of the HTML body to red.
Instead of the body, you can also apply CSS using id or class object.
The code inside the injectedJavaScript
prop is JavaScript String. The code inside the string gets executed after loading the webpage (react-native app here). Just like standard JavaScript, you can use any CSS or JavaScript to manipulate DOM objects.
Make sure, you are cognizant of the code you are injecting as part of injectedJavaScript
. Adding wrong can expose your app to vulnerability.