A Step-by-step Guide to a Consistent Multi-Platform Font Typeface Experience in React Native

Overview

A Step-by-step Guide to a Consistent Multi-Platform Font Typeface Experience in React Native

Goal

Be able to use font typeface modifiers such as fontWeight and fontStyle in combination with a custom font family, in both iOS and Android.

Hello world! Hello world! ">
<Text style={{
  fontFamily: "Raleway",
  fontWeight: "100",
  style: "italic"
}}>
  Hello world!
</Text>
<Text style={{
  fontFamily: "Raleway",
  fontWeight: "bold",
  style: "normal"
}}>
  Hello world!
</Text>

For this example, we are going to register the Raleway font family. Of course, this method will work with any TTF font.

Prerequisites

Assets

You need the whole Raleway font family, extracted in a temporary folder. That is:

  • Raleway-Thin.ttf (100)
  • Raleway-ThinItalic.ttf
  • Raleway-ExtraLight.ttf (200)
  • Raleway-ExtraLightItalic.ttf
  • Raleway-Light.ttf (300)
  • Raleway-LightItalic.ttf
  • Raleway-Regular.ttf (400)
  • Raleway-Italic.ttf
  • Raleway-Medium.ttf (500)
  • Raleway-MediumItalic.ttf
  • Raleway-SemiBold.ttf (600)
  • Raleway-SemiBoldItalic.ttf
  • Raleway-Bold.ttf (700)
  • Raleway-BoldItalic.ttf
  • Raleway-ExtraBold.ttf (800)
  • Raleway-ExtraBoldItalic.ttf
  • Raleway-Black.ttf (900)
  • Raleway-BlackItalic.ttf

We will assume those files are now stored in /tmp/raleway/.

Find the font family name

You will need otfinfo installed in your system to perform this step. It is shipped with many Linux distributions. On MacOS, install it via lcdf-typetools brew package.

otfinfo --family Raleway-Regular.ttf

Should print "Raleway". This value must be retained for the Android setup. This name will be used in React fontFamily style.

Setup

react-native init FontDemo
cd FontDemo

Android

For Android, we are going to use XML Fonts to define variants of a base font family.

Remark: This procedure is available in React Native since commit fd6386a07eb75a8ec16b1384a3e5827dea520b64 (7 May 2019 ), with the addition of ReactFontManager::addCustomFont method.

1. Copy and rename assets to the resource font folder
mkdir android/app/src/main/res/font
cp /tmp/raleway/*.ttf android/app/src/main/res/font

We must rename the font files following these rules to comply with Android asset names restrictions:

  • Replace - with _;
  • Replace any uppercase letter with its lowercase counterpart.

You can use the below bash script (make sure you give the font folder as first argument):

#!/bin/bash
# fixfonts.sh

typeset folder="$1"
if [[ -d "$folder" && ! -z "$folder" ]]; then
  pushd "$folder";
  for file in *.ttf; do
    typeset normalized="${file//-/_}";
    normalized="${normalized,,}";
    mv "$file" "$normalized"
  done
  popd
fi
./fixfonts.sh /path/to/root/FontDemo/android/app/src/main/res/font
2. Create the definition file

Create the android/app/src/main/res/font/raleway.xml file with the below content. Basically, we must create one entry per fontStyle / fontWeight combination we wish to support, and register the corresponding asset name.

">
xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
    <font app:fontStyle="normal" app:fontWeight="100" app:font="@font/raleway_thin" />
    <font app:fontStyle="italic" app:fontWeight="100" app:font="@font/raleway_thinitalic"/>
    <font app:fontStyle="normal" app:fontWeight="200" app:font="@font/raleway_extralight" />
    <font app:fontStyle="italic" app:fontWeight="200" app:font="@font/raleway_extralightitalic"/>
    <font app:fontStyle="normal" app:fontWeight="300" app:font="@font/raleway_light" />
    <font app:fontStyle="italic" app:fontWeight="300" app:font="@font/raleway_lightitalic"/>
    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/raleway_regular" />
    <font app:fontStyle="italic" app:fontWeight="400" app:font="@font/raleway_italic"/>
    <font app:fontStyle="normal" app:fontWeight="500" app:font="@font/raleway_medium" />
    <font app:fontStyle="italic" app:fontWeight="500" app:font="@font/raleway_mediumitalic"/>
    <font app:fontStyle="normal" app:fontWeight="600" app:font="@font/raleway_semibold" />
    <font app:fontStyle="italic" app:fontWeight="600" app:font="@font/raleway_semibolditalic"/>
    <font app:fontStyle="normal" app:fontWeight="700" app:font="@font/raleway_bold" />
    <font app:fontStyle="italic" app:fontWeight="700" app:font="@font/raleway_bolditalic"/>
    <font app:fontStyle="normal" app:fontWeight="800" app:font="@font/raleway_extrabold" />
    <font app:fontStyle="italic" app:fontWeight="800" app:font="@font/raleway_extrabolditalic"/>
    <font app:fontStyle="normal" app:fontWeight="900" app:font="@font/raleway_black" />
    <font app:fontStyle="italic" app:fontWeight="900" app:font="@font/raleway_blackitalic"/>
font-family>
3. Register the new font

In android/app/src/main/java/com/fontdemo/MainApplication.java, bind the font family name with the asset we just created inside onCreate method.

⚠️ If you are registering a different font, make sure you replace "Raleway" with the name found in the former step (find font family name).

--- a/android/app/src/main/java/com/fontdemo/MainApplication.java
+++ b/android/app/src/main/java/com/fontdemo/MainApplication.java
@@ -7,6 +7,7 @@ import com.facebook.react.ReactApplication;
 import com.facebook.react.ReactInstanceManager;
 import com.facebook.react.ReactNativeHost;
 import com.facebook.react.ReactPackage;
+import com.facebook.react.views.text.ReactFontManager;
 import com.facebook.soloader.SoLoader;
 import java.lang.reflect.InvocationTargetException;
 import java.util.List;
@@ -43,6 +44,7 @@ public class MainApplication extends Application implements ReactApplication {
   @Override
   public void onCreate() {
     super.onCreate();
+    ReactFontManager.getInstance().addCustomFont(this, "Raleway", R.font.raleway);
     SoLoader.init(this, /* native exopackage */ false);
     initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
   }

iOS

On iOS, things will get much easier. We will basically just need to use React Native asset link functionality. This method requires that we use the font family name retrieved in the first step as fontFamily style attribute.

Copy font files to assets folder

mkdir -p assets/fonts
cp /tmp/raleway/*.ttf assets/fonts

Add react-native.config.js

module.exports = {
  project: {
    ios: {},
    android: {},
  },
  assets: ['./assets/fonts'],
};

Link

react-native link

You can remove assets for android generated with this command, since we are using the XML Font method. Otherwise, they would be included twice in the app bundle!

rm -rf android/app/src/main/assets/fonts

Result

iOS Android

Postscriptum

If you found this guide relevant, I would greatly appreciate that you upvote this StackOverflow answer. It would also help the community finding out this solution. Cheers!

You might also like...

A FREE Selenium course that takes you step-by-step through building a custom Selenium Framework from scratch.

A FREE Selenium course that takes you step-by-step through building a custom Selenium Framework from scratch.

Selenium For Everyone The book and code repo for the FREE Selenium For Everyone book by Kevin Thomas. FREE Book Download Chapter 1: Getting Started Th

May 10, 2022

Sceneform React Native AR Component using ARCore and Google Filament as 3D engine. This the Sceneform Maintained Component for React Native

Sceneform React Native AR Component using ARCore and Google Filament as 3D engine. This the Sceneform Maintained Component for React Native

Discord Server Join us on Discord if you need a hand or just want to talk about Sceneform and AR. Features Remote and local assets Augmented Faces Clo

Dec 17, 2022

With react-native-update-in-app library you can easily implement in-app updates in your React Native app using CDN or any other file server

React Native In-App update With react-native-update-in-app library you can easily implement in-app updates in your React Native app using CDN or any o

Dec 21, 2022

A cross-platform Mod for the popular Minecraft project, where the border always has a radius equal to the player's current experience level.

A cross-platform Mod for the popular Minecraft project, where the border always has a radius equal to the player's current experience level.

Level = Border A cross-platform Mod for the popular Minecraft project, where the border always has a radius equal to the player's current experience l

Nov 22, 2022

uniVocity-parsers is a suite of extremely fast and reliable parsers for Java. It provides a consistent interface for handling different file formats, and a solid framework for the development of new parsers.

uniVocity-parsers is a suite of extremely fast and reliable parsers for Java. It provides a consistent interface for handling different file formats, and a solid framework for the development of new parsers.

Welcome to univocity-parsers univocity-parsers is a collection of extremely fast and reliable parsers for Java. It provides a consistent interface for

Dec 15, 2022

A strongly consistent distributed transaction framework

A strongly consistent distributed transaction framework

A strongly consistent distributed transaction framework

Jan 3, 2023

Z is a Java library providing accessible, consistent function combinators.

Fearless function combination in Java Techniques Unlock your functional programming potential with these combination techniques: Fusion Z.fuse(fn1, fn

Jun 13, 2022

Reference implementation for MINAS (MultI-class learNing Algorithm for data Streams), an algorithm to address novelty detection in data streams multi-class problems.

Reference implementation for MINAS (MultI-class learNing Algorithm for data Streams), an algorithm to address novelty detection in data streams multi-class problems.

Sep 7, 2022

Spring Native provides beta support for compiling Spring applications to native executables using GraalVM native-image compiler.

Spring Native provides beta support for compiling Spring applications to native executables using GraalVM native-image compiler.

Spring Native provides beta support for compiling Spring applications to native executables using GraalVM native-image compiler.

Jan 6, 2023

React native wrapper for Jitsi Meet SDK Library that rely on the native view (Activity / ViewController)

react-native-jitsi-meet-sdk React native wrapper for Jitsi Meet SDK Library. This Library implements the Jitsi SDK with a native activity on the Andro

May 2, 2022

An awesome native wheel picker component for React Native.

An awesome native wheel picker component for React Native.

⛏️ react-native-picky An awesome native wheel picker component for react-native. Features Supports multiple columns ✅ Supports looping ✅ Native Androi

Dec 4, 2022

KakaoSDK Bridge for React, React-Native, RNW

KakaoSDK Bridge for React, React-Native, RNW

KakaoSDK for React, React-Native Use Dependencies iOS Android Web 2.5.0 2.5.0 1.39.14 처음 설치 시 주의 사항 (React-Native 만) 해당 모듈은 Swift로 되어있어서 그냥 가동 시 작동이 안

May 2, 2022

The react-native Baidu voice library provides voice recognition, voice wake-up and voice synthesis interfaces. react-native百度语音库,提供语音识别,语音唤醒以及语音合成接口。

The react-native Baidu voice library provides voice recognition, voice wake-up and voice synthesis interfaces. react-native百度语音库,提供语音识别,语音唤醒以及语音合成接口。

react-native-baidu-asr react-native-baidu-asr It is a Baidu speech library under React Native, which can perform speech recognition, speech wake-up an

Oct 12, 2022

Cloud native multi-runtime microservice framework

Cloud native multi-runtime microservice framework

Femas: Cloud native multi-runtime microservice framework The repository address has been transferred to PolarisMesh English | 简体中文 Introduction abilit

Sep 5, 2022

Cloud native multi-runtime microservice framework

Cloud native multi-runtime microservice framework

Femas: Cloud native multi-runtime microservice framework Show me femas username:admin password:123456 If you like,star fork it and join us English | 简

Apr 23, 2022

Modern Java - A Guide to Java 8

Modern Java - A Guide to Java 8 This article was originally posted on my blog. You should also read my Java 11 Tutorial (including new language and AP

Jan 5, 2023

Modern Java - A Guide to Java 8

Modern Java - A Guide to Java 8 This article was originally posted on my blog. You should also read my Java 11 Tutorial (including new language and AP

Dec 29, 2022
Comments
  • About iOS Problem

    About iOS Problem

    Thank you for your kind report.

    Your react-native-font-demo is really helpful for me.

    I finished my job about android, but iOS is still not working.

    It says that "Unrecognised font family".

    Is there any way to solve this problem?

    Thanks :D

    opened by chansoo04 1
  • Duplicate Assets

    Duplicate Assets

    Hello!

    We are truly grateful for your solution, however we do have 1 problem.

    Currently the fonts assets will be duplicated ( assets/fonts and android/app/src/main/res/font).

    Is there a way to only include the fonts one in your react-native app?

    opened by DaveyNedap 1
Owner
Jules Sam. Randolph
Build the wheel!
Jules Sam. Randolph
Modern Java - A Guide to Java 8

Modern Java - A Guide to Java 8 This article was originally posted on my blog. You should also read my Java 11 Tutorial (including new language and AP

Benjamin Winterberg 16.1k Jan 5, 2023
React Native Typescript Boilerplate

React Native TypeScript Boilerplate Included Packages react-native-rename react-native-dotenv Instructions Basic instructions To start the development

Frans Slabbekoorn 5 Nov 27, 2021
Leveraging Java 8, create an API with a multi-tier user system.

Project 0 Description Leveraging Java 8, create an API with a multi-tier user system. You may choose the actual use case for your application as long

null 1 Jan 9, 2022
A simplified and multi-functional tool for spigot developers

A simplified and multi-functional tool for spigot developers. There are dozens of features you can use in it, and it is completely open source code. hCore supports all versions from 1.8.x to 1.18.2. Also you can find all these APIs usages from here.

Hakan Kargın 57 Jan 1, 2023
JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface that is bound to the external C library using method names.

JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface t

null 28 Dec 30, 2022
Simple way of causing a bsod using the native api implemented into a 1.12.2 Forge mod

Simple-BSOD-Mod Simple way of causing a bsod using the native api implemented into a 1.12.2 Forge mod. Dowload It HERE To make your own you can go to

INZO_Technologies 5 Dec 28, 2022
Engin Demiroğ - Yazılımcı Geliştirme (JAVA + REACT) Yerleştirme Kampı 4. Gün 1. Ödev

JavaCampD4HomeWork1 Engin Demiroğ - Yazılımcı Geliştirme (JAVA + REACT) Yerleştirme Kampı 4. Gün 1. Ödev Kimlik Doğrulama Servisi (MERNIS) Projeye Nas

Berkcan 4 Jun 4, 2021
Repository for AMES Amperes 2022 Rapid React season

Repository for AMES Amperes 2022 Rapid React season

null 3 Nov 10, 2022
BitBase is a Client-Server based Crypto trading platform which offers live pricing, dynamic charts, user portfolio, account settings... and much more!

BitBase-Crypto-Trading-Platform BitBase is a Client-Server based Crypto trading platform which offers live pricing, dynamic charts, user portfolio, ac

null 4 Feb 11, 2022
JHipster Lite ⚡ is a development platform to generate, develop & deploy modern web applications & microservice architectures, step by step.

JHipster Lite ⚡ Description JHipster is a development platform to quickly generate, develop & deploy modern web applications & microservice architectu

JHipster 255 Jan 3, 2023