How to use custom fonts in React Native?
Fonts… every application has one, and your React Native application should be no different. Today we will learn how to add custom fonts to iOS and Android when building your app with React Native.
Setup
One of the pitfalls of adding fonts in React Native is that the name of the font you are using has to match when referenced in JavaScript. Android will use the font name, but iOS will use the ‘PostScript name’.
In the above case, the font name and ‘PostScript name’ are the same, but if they are not, rename your file to match the ‘PostScript name’, to avoid unnecessary conditionals in your code.
Next step is to add the fonts to our react native project, to do this we define an assets directory, in our example this will be at the root of our project and the fonts will be in the following directory assets/fonts
.
As of React Native 0.60, rnpm has been deprecated, and the way to link fonts differs slightly depending on your version of react native, you can check the migration guide for more info.
React Native 0.60+
Create a react-native.config.js file at the root of the project.
Add the following code to your react-native.config.js file.
Run npx react-native link
and the auto-linking feature in React Native 0.60 will perform its magic and you will be able to use your fonts in your application (see below for using fonts in JavaScript) 🎉
React Native 0.59 or below
Just like the example above we need to tell React Native where to find our fonts. We do this using rnpm and the package.json.
Add the following block of code to your package.json.
"rnpm": {
"assets": [
"./assets/fonts"
]
},
React Native 0.59 or versions below do not come with auto-linking, so you must run the react-native link
command in your terminal.
For Android this command will create a fonts directory android/app/src/main/assets/fonts, and for iOS it will add fonts to your Info.plist.
Manual Linking
You can also link fonts manually on iOS and Android. This is also important to note if you want to remove fonts. As you can only remove fonts manually after they have been linked with the React Native link command.
To add / remove fonts in Android you have to find the android/app/src/main/assets/fonts directory, and add / remove fonts from there.
On iOS adding / removing fonts is a little trickier, you must add / remove your fonts from the /resources folder and the Info.plist.
One thing to note is that when you add font files to your iOS project, make sure you add them to your target and tick “Copy items if needed”
The apple developer documentation covers adding fonts in detail.
Usage
Now, to use fonts in your application, add the fontFamily
attribute to the style of a React Native <Text style={{ fontFamily: "Montserrat-Bold" }} />
component.
For further reading on this topic see Custom Font Caveats in React Native.