How to load custom font to your react native project
Adding custom fonts in React Native 0.60+
Most recommended font files should be either in .ttf or .otf format. However you can get your font from any source here we will be using Google Fonts.
To add fonts to React Native project (0.60+) with the following steps.
For Bare React Native Project
- Get the font files needed for the project
Go to Google Fonts, select and download your desired fonts.
- Creating a font for your fonts
In your react native project, go to the assets folder (if you do not have any, your can create) and create a folder named fonts under the assets directory and place the fonts files you downloaded in it.
- Create a configuration file Create a configuration file named react-native.config.js in the root project directory and add the following code:
module.exports = {
project: {
ios:{},
android:{}
},
assets:['./assets/fonts/'],
}
- Link the font assets
npx react-native link
OR
yarn react-native link
For React Native Expo
- Get the font files needed for the project
Go to Google Fonts, select and download your desired fonts.
- Creating a font for your fonts
In your react native project, go to the assets folder (if you do not have any, your can create) and create a folder named fonts under the assets directory and place the fonts files you downloaded in it.
- Install packages to make it work
expo install expo-font
- Importing the font from expo-font package
import * as Font from "expo-font";
Creating a function to load the font
const getFonts = () => Font.loadAsync({ GelasioItalic: require("./assets/fonts/Gelasio-Italic.ttf"), });
Configuring the font to your project
import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View } from "react-native";
import * as Font from "expo-font";
import { useEffect } from "react";
const getFonts = () =>
Font.loadAsync({
GelasioItalic: require("./assets/fonts/Gelasio-Italic.ttf"),
});
export default function App() {
useEffect(() => {
// To load the font on every render of your project
getFonts();
}, []);
return (
<View style={styles.container}>
<Text style={styles.header}>
Open up App.js to start working on your app!
</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
header: {
fontFamily: "GelasioItalic",
fontSize: 20,
},
});