Nona Blog

Using Google Fonts with React Native Expo

Expo recently released their version 38 of the Expo SDK.

This release features the new google fonts package @expo-google-fonts which allows users to easily use any of the 991 fonts (and their variants) from fonts.google.com in an Expo app.

These packages and all fonts work across web, iOS and Android, and are free to use and open source.

Let’s get started and see how we can easily add fonts to our App.

First we start by installing the package for the font we want. I’m going to use
Nunito Sans for this example.

expo install @expo-google-fonts/nunito-sans
npm install expo-google-fonts/nunito-sans

If you can’t find the font you are looking for, here’s a link to website which lists all the available fonts as well as the package names and import statements.

https://directory.now.sh/

Once this is installed we can import the variations of the font that we need.

import {
  NunitoSans_200ExtraLight,
  NunitoSans_400Regular 
} from '@expo-google-fonts/nunito-sans'

Before we move on, all of the font packages include the useFonts hook. So we need to import this as well.

import {
  useFonts,
  NunitoSans_200ExtraLight,
  NunitoSans_400Regular 
} from '@expo-google-fonts/nunito-sans'

Next let’s import the AppLoading component.

import { AppLoading } from 'expo'

Now we need to get our fonts loaded into the App, to do this we will use the useFonts hook. The hook will return a boolean if the fonts were loaded correctly and an error if they were not.

const Authenticate = () => {
  let [fontsLoaded, error] = useFonts({ 
    NunitoSans_200ExtraLight,
    NunitoSans_400Regular
  })
...

Now that we’ve loaded the fonts, we want to make sure that it is fully loaded before we try to render it. So we’ll check if it’s not loaded and return the AppLoading component if this is the case.

if (!fontsLoaded) { 
  return <AppLoading /> 
}

Now let’s actually display it. The font family we use corresponds to how it was loaded in the useFonts hook section.

return (
  <View style={{
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center'}} >
    <Text style={{
      fontFamily: 'NunitoSans_200ExtraLight'}}>
        NunitoSans ExtraLight
    </Text>
    <Text style={{
      fontFamily: 'NunitoSans_400Regular'}}>
        NunitoSans Regular
    </Text>
  </View>
)

Thanks for following!  🦾
I hope this article was useful. If you’re still struggling here’s a link to the official Github documentation https://github.com/expo/google-fonts .

Add comment