How to load font in App.js and use in whole project.

#1

I can’t able to load and apply the custom font in my project.
I’m loading it in my App.js like below:

state = {
fontLoaded: false,
};

async componentDidMount() {
await Font.loadAsync({
‘bungee_regular’: require(’./assets/fonts/FontFileName.ttf’)
});
console.log(‘Font loaded.!’);
this.setState({ fontLoaded: true });
}

And then I am using it in Home.js like
<Text style={{ fontFamily: myFontName}}>Apply font</Text>
but not working
What’s wrong with this.
Thanks in advance…!!!

#2

You have to pass down the fontLoaded state as a prop to Home, so that you re-render when the font has loaded. If you don’t want to render any text until the font has loaded, do this:

<View>
  {
    this.props.fontLoaded ? (
      <Text style={{ fontFamily: 'your-font'}}>
        Hello, world!
      </Text>
    ) : null
  }
</View>

Alternatively, you can have App.js render null or <AppLoading /> until the font is loaded.
There’s a full tutorial here: https://docs.expo.io/versions/v31.0.0/guides/using-custom-fonts

#3

I don’t have the fontLoaded variable in the Home.js file.
I wrote the condition in the App.js , how can I access the fontLoaded in the Home.js file.

In my App.js file
render() {
if (this.state.fontLoaded === true) {
return <AppStackNavigator />
}
}

#4

I am using the font in the Home.js, is it possible to access the fontLoaded declared the APp.js in the Home.js file.

#5

Oh, what you’re doing looks like it should work, since you don’t render Home.js until the font is loaded. When you say it’s not working, what do you see? Is it using the default font, or not appearing, or do you get an error?

#6

I have to load the custom font in App.js file ,and have to use the loaded custom fonts in the entire project.
When I write the below in App.js
if (this.state.fontLoaded === true) {

return (this.state.fontLoaded ? <AppStackNavigator /> : null);
}
And when I use the font in any .js file ,it gives me the error
fontname is not a system font.
Is there any permanent solution for this issue.

#7

Hmm. Can you double check you’re using the exact same font name 'bungee_regular' in both places? Also, can you verify from the console logs that the error occurs after the Font loaded log?

#8

I caught the error.
It’s nothing related to anything else.
It’s just happening due to using the fontWeight, some fonts are not loaded if fontWeight property is used.

closed #9

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.