Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/jsamr/react-native-font-demo

A demo for Android font typeface support in React Native!
https://github.com/jsamr/react-native-font-demo

android font fonts react-native typeface

Last synced: 5 days ago
JSON representation

A demo for Android font typeface support in React Native!

Awesome Lists containing this project

README

        

# 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.

```jsx

Hello world!

Hello world!

```

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](https://fonts.google.com/share?selection.family=Raleway:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900), 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.

```sh
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

```sh
react-native init FontDemo
cd FontDemo
```

#### Android

For Android, we are going to use [XML Fonts](https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml) to define variants of a base font family.

> **Remark**: This procedure is available in React Native since commit [fd6386a07eb75a8ec16b1384a3e5827dea520b64](https://github.com/facebook/react-native/commit/fd6386a07eb75a8ec16b1384a3e5827dea520b64) (7 May 2019 ), with the addition of `ReactFontManager::addCustomFont` method.

##### 1. Copy and rename assets to the resource font folder

```sh
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):

```bash
#!/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
```

```sh
./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


















```

##### 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.

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

```diff
--- 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());
}

```

**On React Native 0.73+**

```diff
--- a/android/app/src/main/java/com/fontdemo/MainApplication.kt
+++ b/android/app/src/main/java/com/fontdemo/MainApplication.kt
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
+import com.facebook.react.common.assets.ReactFontManager
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost

override fun onCreate() {
super.onCreate()
+ ReactFontManager.getInstance().addCustomFont(this, "Raleway", R.font.raleway);
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}

```

## 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

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

### Add `react-native.config.js`

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

### Link

```sh
# react-native >= 0.69
npx react-native-asset

# otherwise
react-native link
```

## Result

iOS
Android


## Postscriptum

If you found this guide relevant, I would greatly appreciate that you upvote [this StackOverflow answer](https://stackoverflow.com/a/70247374/2779871). It would also help the community finding out this solution. Cheers!