javascriptreact-nativefont-familyreact-native-svg

Custom fonts are not rendered in RN-SVG <Text/>


In my code I tried to:

import { useFonts } from 'expo-font'

useFonts( {
  'Robo Numbers':require( '../assets/fonts/my-custom.ttf' ),
} )

Now when I render the RN own or RN-Paper's Text element, the font-family properly shows up:

import { Text } from 'react-native-paper'
const styles = StyleSheet.create({
  countdown:{
    fontFamily:'Robo Numbers', 
    fontSize:34,
  },
})

 <Text style={[ styles.countdown, { color:10 > countdown ? 'orange' : '#f8f0c1' } ]}>{countdown}</Text>

but in RN-SVG's Text the default font is rendered:

<Text stroke={10 > countdown ? 'orange' : '#f8f0c1'} fontFamily="Robo Numbers">{countdown}</Text>

Is the functionality missing in the library, or am I missing something?


Solution

  • As of now "react-native-svg": "~13.4.0" the custom fonts are not supported or I could not find the DOCUMENTED way to use them.

    Hence I found a pretty uncomplicated workaround based on <ForeignObject/>:

    render() {
      const { countdown } = this.state
    
      return <>
        <ForeignObject x={85} y={94} height={14} key={countdown}>
          <Text style={{ fontFamily:'Robo Numbers' }}>{countdown}</Text>
        </ForeignObject>
      <>
    }
    

    The CRITICAL thing here is the ForeignObject@key attribute. It must be present to force the ForeignObject re-render it's children.

    In my case I increment the countdown variable within setInterval(), but the text never got updated before I added the ForeignObject@key with ever changing value!

    Hope this will help someone...