I am a beginner learning React Native and I am trying to include custom fonts (.ttf files) in my application.
I get warnings like these:
fontFamily "DMRegular" is not a system font and has not been loaded through expo-font
This is what I have done in my _layout.js file:
import { Stack } from 'expo-router'
import { useCallback } from 'react'
import { useFonts } from 'expo-font'
import * as SplashScreen from 'expo-splash-screen'
SplashScreen.preventAutoHideAsync()
const Layout = () => {
const [fontsLoaded] = useFonts({
DMBold: require('../assets/fonts/DMSans-Bold.ttf'),
DMRegular: require('../assets/fonts/DMSans-Regular.ttf'),
DMMedium: require('../assets/fonts/DMSans-Medium.ttf'),
})
const onLayoutRootView = useCallback(async () => {
if(fontsLoaded) {
await SplashScreen.hideAsync();
}
}, [fontsLoaded])
if(!fontsLoaded) return null;
return <Stack onLayout={onLayoutRootView} />;
}
I am trying to use the custom fonts like this:
const styles = StyleSheet.create({
welcomeMessage: {
fontFamily: "DMBold",
fontSize: SIZES.xLarge,
color: COLORS.primary,
marginTop: 2,
}
Please, any help would be much appreciated.
Versions:
"expo": "~50.0.14"
"expo-font": "~11.10.3"
2
Answers
To include custom fonts in your React Native application using Expo, you need to follow these steps:
Import Expo Font: Make sure you import expo-font in your project.
Load Fonts: Use Font.loadAsync() to load your custom fonts before rendering any UI components that use them.
Use Custom Fonts: Once the fonts are loaded, you can use them in your styles by specifying the fontFamily.
Here’s how you can do it in your _layout.js file:
Font.loadAsync().
fonts have been loaded.
which displays a loading screen until the fonts are loaded.
For React.js web applications, you would typically use CSS to load custom fonts. You can either import the font files directly into your project and use the CSS @font-face rule to define the font, or you can use web font services like Google Fonts or Adobe Fonts.
Here’s a basic example of using custom fonts in a React.js web application:
fonts.
CSS file or using a CSS-in-JS solution like styled-components
Apply the custom font to elements in your React components using CSS