How to set custom fonts in WebView(react-native-webview) in iOS?

Viewed 2674

I want to set custom fonts in Webview. I have implemented the below code:

@font-face {
    font-family: 'Poppins-Bold'; 
    src:url('file:///android_asset/fonts/Poppins-Bold.ttf') format('truetype')
}
body{
    font-family: Poppins-Bold
    margin: 0;
    padding: 0;
    color: red;
}

It works fine in android, but it does not working in iOS. Let me know if anybody has a solution for this.

Note: I don't want to use google's CSS font

1 Answers
  1. Set the following font URL based on platform:
    const fontUrl = Platform.select({
        ios: "Poppins-Bold.ttf",
        android: "file:///android_asset/fonts/Poppins-Bold.ttf",
    });
    
  2. Update your CSS styles to the following:
     const css = `
         @font-face {
            font-family: 'Poppins-Bold'; 
            src: local('Poppins-Bold') url('${fontUrl}') format('truetype')
         }
         body {
            font-family: Poppins-Bold
            margin: 0;
            padding: 0;
            color: red;
         }`
    
    • Note that format('truetype') is used since your font extension is ttf. If you're using an eot font you'll need to use format('opentype').
  3. Once you do that, update your WebView component with the following props:
    <WebView 
        source={{ html, baseUrl: '' }}
        originWhitelist={["*"]}
    />
    
    • Setting baseUrl to blank will ensure fonts are loaded. Reference this post.
    • Without setting originWhitelist, you'll get errors on iOS that the URL cannot be found.

This worked for me on both Android & iOS and I happen to be using Poppins as well

Related