Published on

Custom fonts in React Native (Expo)

Expo is a great platform for new comers to React Native and for building fast prototypes without having to meddle with Android or iOS code. When building an application, you will want to use custom fonts in your app. Expo makes using custom fonts really really simple

To get started, download the font you want to use in your app in .ttf or .otf format. Create a directory in the assets folder and name it fonts. Place all your font files here.

Now you will need to install a package that provides a hook called useFonts

yarn add @use-expo/font

or

npm install --save @use-expo/font

In your App.js file, import the hook

import { useFonts } from '@use-expo/font';

Then use the hook to load all the fonts

const [isLoaded] = useFonts({
  'SourceSans-ExtraLight': require('./assets/fonts/SourceSansPro-ExtraLight.ttf'),
  'SourceSans-Light': require('./assets/fonts/SourceSansPro-Light.ttf'),
  'SourceSans-Regular': require('./assets/fonts/SourceSansPro-Regular.ttf'),
  'SourceSans-SemiBold': require('./assets/fonts/SourceSansPro-SemiBold.ttf'),
  'SourceSans-Bold': require('./assets/fonts/SourceSansPro-Bold.ttf'),
  'SourceSans-Black': require('./assets/fonts/SourceSansPro-Black.ttf'),
})

Note that this process is asynchronous so you will have to show a loading indicator meanwhile. For this, you can import AppLoading from Expo.

import { AppLoading } from 'expo'

And then if loaded is false, return AppLoading

To use the font you can provide the font name in the styles object

<Text style={{ fontFamily: 'SourceSans-Regular' }}>Hello World</Text>

See below for a complete implementation

import React from 'react'
import { Text, View } from 'react-native'
import { useFonts } from '@use-expo/font'
import { AppLoading } from 'expo'

export default function App() {
  const [isLoaded] = useFonts({
    'SourceSans-ExtraLight': require('./assets/fonts/SourceSansPro-ExtraLight.ttf'),
    'SourceSans-Light': require('./assets/fonts/SourceSansPro-Light.ttf'),
    'SourceSans-Regular': require('./assets/fonts/SourceSansPro-Regular.ttf'),
    'SourceSans-SemiBold': require('./assets/fonts/SourceSansPro-SemiBold.ttf'),
    'SourceSans-Bold': require('./assets/fonts/SourceSansPro-Bold.ttf'),
    'SourceSans-Black': require('./assets/fonts/SourceSansPro-Black.ttf'),
  })

  if (!isLoaded) {
    return <AppLoading />
  } else {
    return (
      <View>
        <Text style={{ fontFamily: 'SourceSans-Regular' }}>Hello World</Text>
      </View>
    )
  }
}

Did you like what you read?

You can follow me on Twitter or LinkedIn to get notified when I publish new content.