How to add and remove custom fonts in React Native

Every time when I need to include fonts to my React Native project for IOS and Android I start to google searching ‘that one tutorial with fewer steps’ to make it faster. And every time it takes much more time than I expect to. So I found a better faster and shorter solution which takes several lines of code.

Let’s start! 🚀

https://reactn.slack.com/shared_invite/MTg4NjkzNTk2NjMwLTE0OTU3MTA2ODMtZWJhMDIwMWM0Yg

Adding / Linking fonts for IOS and Android at once

1. First step

Collect all fonts you want to use for IOS and Android and place it in the directory inside your project. For example in ./assets/fonts/

2. Second step

Add the following line in your package.json:

“rnpm”: {
“assets”: [“./path to your fonts”]
}
in our example path is - ./assets/fonts

3. Third step

And finally, run in terminal:

$ react-native link

After running link command you should see something like this in your terminal output:

$ react-native link result

That’s all! 💥💥💥💥💥 We are done. All your fonts are linked and can be used for both IOS and Android.

Here is a bit of explanation of what’s going on:
rnpm — is react native package manager which now is part of React Native core. For earlier usage, we would need to rewrite the third step to rnpm link, but now react-native recognize `link` command by itself.
So on third step packager links fonts in Info.plst for IOS and creates fonts directory (android/app/src/main/assets/fonts) for Android, where copies your fonts

Removing / Unlinking fonts for IOS and Android

We saw above how to link fonts but unfortunately, there is no analog command for unlinking already linked fonts. Let’s see how we can do this.

Android:

Just remove fonts from the directory which was created by react-native link command. This directory is located in:

android/app/src/main/assets/

IOS:

For IOS there is a little bit longer path.

1. First step

Remove all fonts you want to delete from Info.plist file by opening XCode:

Info.plist

2. Second step

Remove all fonts left linked in XCode underBuild Phases > Copy Bundle Resources

MyProject > Build Phases > Copy Bundle Resources

NOTE:

After removing fonts you may be facing some errors from XCode like:

Error after removing fonts

Just skip it. This error appears because XCode sees a discrepancy between the previous git commit and the current state of your fonts folder. This message will disappear as soon as you will do git commit with your changes.

That’s all, folks!
Stay tuned & happy coding ;)
Daniel