How do I set custom fonts in React Native?

102 Views Asked by At

My code is as follows:

import { StatusBar } from 'expo-status-bar';
import Home from './screens/home';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { AppLoading } from 'expo-app-loading';


const getFonts = () => Font.loadAsync({
  'montserrat-regular': require('./assets/fonts/Montserrat-Regular.ttf'),
  'montserrat-medium': require('./assets/fonts/Montserrat-Medium.ttf'),
  'wreath': require('./assets/fonts/insigne - Wreath Halftone Medium.otf'),
});

export default function App() {

  const [fontsLoaded, setFontsLoaded] = useState(false);

  if(fontsLoaded)
  {
    return (
      <Home />
    );
  } else{
    return(
      <AppLoading
        startAsync = {getFonts}
        onFinish={() => setFontsLoaded(true)}
      />
    )
  }
}

and this is showing the following error:

Render Error
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of 'App'.

The fonts should work as I am learning but it's throwing an error while working propoerly if I remove the fonts

1

There are 1 best solutions below

1
Yakupguly Malikov On

It might be because of your getFonts is not async function. Try making it async like below:

const getFonts = async () => await Font.loadAsync({
  'montserrat-regular': require('./assets/fonts/Montserrat-Regular.ttf'),
  'montserrat-medium': require('./assets/fonts/Montserrat-Medium.ttf'),
  'wreath': require('./assets/fonts/insigne - Wreath Halftone Medium.otf'),
});