Tips for enabling custom fonts in the latest expo software update

Update: While running expo start, the fonts are displayed correctly. However, when following the recommended method of using npx expo start, the fonts do not load properly. I even tried integrating Google Fonts using '@expo-google-fonts/montserrat'

I have experimented with various approaches to display the fonts correctly. It works fine with JavaScript but encounters issues in TSX as shown below:

if (!fontsLoaded) {
return null;
}

The app fails to load and only displays a blank white screen. Upon removing if (!fontsLoaded) {return null;}, the following error message appears:

"fontFamily "Inter-Black" is not a system font and has not been loaded through Font.loadAsync."

Even after trying the specified solution from the expo.dev website, I faced the same issue and error.

The current configuration I am working with includes:

    import React, { useEffect, useCallback } from 'react';
    import { LogBox } from 'react-native';
    import * as SplashScreen from 'expo-splash-screen';
    // import 'react-native-gesture-handler';
    import { NavigationContainer } from '@react-navigation/native';
    import { SafeAreaProvider } from 'react-native-safe-area-context';
    import { useFonts } from 'expo-font';
    import HomeNavigator from './src/routes/app.routes';


    export default function App() {
    LogBox.ignoreLogs(["Sending..."]);
    useEffect(() => {}, []);
    const [fontsLoaded] = useFonts({
    'Thin': require('./assets/fonts/Montserrat-Thin.ttf'),
    'Light': require('./assets/fonts/Montserrat-Light.ttf'),
    'ExtraLight': require('./assets/fonts/Montserrat-ExtraLight.ttf'),
    'Regular': require('./assets/fonts/Montserrat-Regular.ttf'),
    'Medium': require('./assets/fonts/Montserrat-Medium.ttf'),
    'Semibold': require('./assets/fonts/Montserrat-SemiBold.ttf'),
    'Bold': require('./assets/fonts/Montserrat-Bold.ttf'),
    'Black': require('./assets/fonts/Montserrat-Black.ttf')
  });

  const onLayoutRootView = useCallback(async () => {
      if (fontsLoaded) {
        await SplashScreen.hideAsync();
      }
    }, [fontsLoaded]);

    if (!fontsLoaded) {
      return null;
    }
    return (
    <SafeAreaProvider>
      <NavigationContainer>
        <HomeNavigator />
      </NavigationContainer>
    </SafeAreaProvider>
    );
    }

A different approach provided by Expo included:

    import { useCallback } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';

SplashScreen.preventAutoHideAsync();

export default function App() {
  const [fontsLoaded] = useFonts({
    'Inter-Black': require('./assets/fonts/Montserrat-Black.ttf'),
  });

  const onLayoutRootView = useCallback(async () => {
    if (fontsLoaded) {
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded]);

  if (!fontsLoaded) {
    return null;
  }

  return (
    <View style={styles.container} onLayout={onLayoutRootView}>
      <Text style={{ fontFamily: 'Inter-Black', fontSize: 30 }}>Inter Black</Text>
      <Text style={{ fontSize: 30 }}>Platform Default</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

Answer №1

If you are encountering an error, consult the documentation for clarification.

Upon examination, it appears that the issue may stem from importing a font with a .ttf file extension while the documentation recommends using the newer .otf format. It is possible that the framework is unable to recognize the old file extension, leading it to search online for the file.

To understand the distinctions between ttf and otf fonts, refer to this resource here. Goodbye

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The DatePicker in Angular2 and Typescript is unable to execute the property 'toggle' because it is undefined

I've encountered an issue with the calendar icon for angular2's datepicker. Whenever I try to click on it, I keep getting this error: TypeError: Cannot read property 'toggle' of undefined at Object.eval [as handleEvent] (Admiss ...

Guide to connecting CameraRoll in React Native and setting it up for use

I have come across numerous tutorials that mention linking CameraRoll, but they fail to provide clear instructions on how to actually link it. I have searched extensively but haven't been able to find a proper guide. I am aware that CameraRoll is alre ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

Error message: "Declared app-routing module in Angular 2 is encountering routing declaration

Currently, I am immersing myself in learning Angular 2 through the official tutorial available at https://angular.io/docs/ts/latest/tutorial/toh-pt5.html. However, I have encountered an issue related to routing. The error message displayed states: Type Das ...

"Step-by-Step Guide: Building a Previous and Continue Button in Angular

I am a beginner with Angular and I am working on adding a Next button to navigate to the next page. However, I want the button to only proceed if the answer to a specific question is yes. If the answer is no, I would like it to skip a part of the page. Hop ...

Bring in the type "Request" from the express-request-id module

Within our web app that utilizes TypeScript and express, we integrated the npm package express-request-id to enhance our HTTP Requests and responses by adding X-Request-Id headers. We crafted a middleware to assign the request's id to the HTTP respon ...

Experiencing migraines while integrating Firebase 9, Redux Toolkit, and Typescript in a React project. Encountering a peculiar issue where 'dispatch' is unexpectedly identified as type 'never'?

I am currently in the process of upgrading an old project to newer technologies, specifically focusing on Typescript, redux-toolkit, and Firebase v9 for modularity. While I have limited experience with Typescript and none with redux-toolkit, I have been us ...

Is there a way to make the Sweetalert2 alert appear just one time?

Here's my question - can sweetalert2 be set to only appear once per page? So that it remembers if it has already shown the alert. Swal.fire({ title: 'Do you want to save the changes?', showDenyButton: true, showCancelButton: true, ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

How to display an object in the template that does not have a specified property

I am dealing with an object that can have a type of WithBalance | WithoutBalance withBalance : { balance:number, name:string } withoutBalance : { name : string} <span>{{object?.balance ?? 0}} </span> However, when I attempt to access the bal ...

Injecting singletons in a circular manner with Inversify

Is it possible to use two singletons and enable them to call each other in the following manner? import 'reflect-metadata'; import { Container, inject, injectable } from 'inversify'; let container = new Container(); @injectable() cla ...

The error message indicates that the property 'toLowerCase' is not found on type 'NonNullable<T[keyof T]>'

I've created a method called filterByFront export const filterByFront = <T>( value: string, jsonData: T[], setData: (data: T[]) => void, filterKey: keyof T ) => { const originData = jsonData; if (!!value && !!value.trim ...

What is the best way to prevent TSC from including the node_modules folder in my compilation

I have encountered a persistent issue that all previous solutions have failed to address. Here is the snippet from my tsconfig file that I believe should resolve the problem: ... "compilerOptions": { "skipLibCheck": true, ... &quo ...

The parameter 'string | JwtPayload' cannot be assigned to the parameter 'string'

Utilizing Typescript alongside Express and JWT for Bearer Authorization presents a specific challenge. In this situation, I am developing the authorize middleware with JWT as specified and attempting to extricate the current user from the JWT token. Sampl ...

Utilizing class-validator for conditional validation failure

Implementing conditional validation in the class-validator library using the given example, I need to ensure that validation fails if the woodScrews property is assigned a value when the tool property is set to Tool.TapeMeasure. I've searched extensiv ...

Struggling with slow TypeScript compilation?

My current setup involves TypeScript 2.2.1, but I've been facing prolonged compilation times when running tsc. In an attempt to gather more information, I decided to utilize the --diagnostics option. However, I soon discovered that the "Total time" di ...

Is it possible to send prop as an object property in a TypeScript-based React component?

I am struggling with a persistent issue: export const LIST_OF_TYPES = { TYPE1: 'type1', TYPE2: 'type2', }; In the element, I specify the classification as such: export type IComponentCategoryType = 'type1' | 'type2&a ...

Error in Firebase Functions: missing 'Access-Control-Allow-Origin' header

I recently followed a tutorial but used nodemailer instead of sendgrid. https://www.youtube.com/watch?v=wCtNjP9gcqk Encountered this error: The response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origi ...