Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google fonts in React Native

I was wondering if it'd be possible to use Google fonts in my React Native project.

I've been looking for some information but I didn't find anything.

Is it possible?

Thanks.

P.D.: I know I can download it and include it into my project.

like image 579
JV Lobo Avatar asked Nov 28 '15 12:11

JV Lobo


People also ask

Can we use OTF fonts in React Native?

In order to add your font to your app, you'll need the . ttf (other formats such as . otf are also supported) files for all supported styles (bold, italic ...) or sample depending your need.


1 Answers

If your React Native project was bootstrapped with the Expo CLI, you can now incorporate Google Fonts into the project using the expo-google-fonts package.

Install the packages:

expo install @expo-google-fonts/dev expo-font

Note: dev will allow you to import any font style from any of the Expo Google Fonts packages. This will load fonts over the network at runtime instead of adding the asset as a file to the project (good if you don't know what font to use):

import {
  useFonts,
  Roboto_400Regular,
  Bangers_400Regular,
  OpenSans_400Regular
} from "@expo-google-fonts/dev";

If on the other hand you already know what font you're going to use, run:

expo install @expo-google-fonts/FONT_FAMILY_NAME expo-font

For example, if you choose to use Roboto we would install:

expo install @expo-google-fonts/roboto expo-font

To avoid rendering text before the font is loaded, install the expo-app-loading package to use the <AppLoading /> component:

expo install expo-app-loading

Then in your project file use the font like this:

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { AppLoading } from "expo-app-loading";
import {
  useFonts,
  Roboto_400Regular,
  Roboto_400Regular_Italic
} from "@expo-google-fonts/roboto";

export default function App() {
  let [fontsLoaded] = useFonts({
    Roboto_400Regular,
    Roboto_400Regular_Italic
  });

  if (!fontsLoaded) {
    return <AppLoading />;
  } else {
    return (
      <View style={{flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text style={{ fontFamily: "Roboto_400Regular", fontSize: 28 }}>
          Nice! Support for Google Fonts!
        </Text>
      </View>
    );
  }
}
like image 149
Juan Marco Avatar answered Sep 17 '22 07:09

Juan Marco