Reputation: 1397
I am trying to set default font(Lato-Regular) in RN Expo project.
I am using setCustomText to achieve this. https://github.com/Ajackster/react-native-global-props
This approach worked when running in non-expo project like a charm but now I am moving my project to Expo and seem to have a problem with default font for the app.
import React, { Component } from 'react'
import { Styles } from 'react-native'
import { Root } from './src/config/router'
import {
setCustomText
} from 'react-native-global-props'
import { Font } from 'expo'
class App extends Component {
constructor() {
super()
this.state = {
currentTab: null,
fontLoaded: false
}
}
getCurrentRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index]
if (route.routes) {
return this.getCurrentRouteName(route)
}
return route.routeName;
}
componentDidMount() {
Font.loadAsync({
'Lato-Regular': require('./src/assets/fonts/Lato-Regular.ttf')
});
this.setState({
fontLoaded: true
},
() => this.defaultFonts());
}
defaultFonts(){
const customTextProps = {
style: {
fontFamily: 'Lato-Regular'
}
}
setCustomText(customTextProps)
}
render() {
console.log( this);
return (
this.state.fontLoaded ?
<Root
screenProps={{currentScreen: this.state.currentTab}}
/> : null
)
}
}
export default App
But I get this error:
What might be the problem
Upvotes: 7
Views: 13177
Reputation: 7578
Here you are not waiting the font to be loaded, you call setState
instantly after requesting the font. You have to wait the Font.loadAsync
Promise to be resolved.
componentDidMount() {
Font.loadAsync({
'Lato-Regular': require('./src/assets/fonts/Lato-Regular.ttf')
})
.then(() => {
this.setState({ fontLoaded: true });
this.defaultFonts();
});
}
You can also use the async/await
syntax.
async componentDidMount() {
await Font.loadAsync({
'Lato-Regular': require('./src/assets/fonts/Lato-Regular.ttf')
})
this.setState({ fontLoaded: true });
this.defaultFonts();
}
Upvotes: 3