Easiest way to use custom fonts in React-Native
Simple guide to setup custom fonts in React Native.
(version 0.62)
Steps -
- Download the fonts which you need
- Place the fonts in your project directory
- Create Config file
- Link the fonts in your project
- How to use the fonts in the code
Step 1:
Visit Google Fonts and download the font you want to use in your project.
- Find the font you want
- Click on the Plus icon to add the font
- This will add the font in a popup at bottom-right with the title ‘Families Selected’
- You can customize the font variants you need and hit the download button.
Result: This should download a zip file with the font you selected with various .ttf files
Step 2:
Place the font files in your project directory in a folder named ‘fonts’
Note: This path is to be used in the next
Step 3:
Creating the config file:
- Create a new file in the root directory of your project:
react-native.config.js - Add the code below in the file with the path where you stored your files
Note: After React-Native version 0.60 we are no longer using rnpm.
Hence the older guides won’t be useful where the next step was to setup rnpm in package.json
Step 4:
Link the fonts in your project
Run the command below in the terminal
For React-Native versions below 0.69<
react-native link
For React-Native versions above 0.69≥
react-native-asset
You should see something like this in the terminal:
// Remember to run this
react-native run-android
Note: Sometimes the auto linking fails for android and pushes the files to wrong path
Wrong path -android/src/main/assets/fonts
Path should be -android/app/src/main/assets/fonts
Step 5:
How to use the fonts in the code
<Text style={{fontFamily: 'OpenSans-Regular' }}>Text</Text><Text style={{fontFamily: 'OpenSans-Bold' }}>Text</Text><Text style={{fontFamily: 'OpenSans-SemiBold' }}>Text</Text>
Remember use them according to their file names.
There is NO need to use:
fontWeight: 'bold' // This is incorrect. Use: OpenSans-BoldORfontStyle:'italic' // This is incorrect. Use: OpenSans-Italic
This will in fact result into unwanted results.
Now you should be able to use the fonts anywhere in your project.
Thank you for Reading. ^_^
Join me at Plant-for-the-planet to develop an open source app to Fight Climate Change.