Using custom fonts in react native

50 views Asked by At

I am a beginner learning React Native and I am trying to include custom fonts (.ttf files) in my application.

I get warnings like these:

fontFamily "DMRegular" is not a system font and has not been loaded through expo-font

This is what I have done in my _layout.js file:

import { Stack } from 'expo-router'
import { useCallback } from 'react'
import { useFonts } from 'expo-font'
import * as SplashScreen from 'expo-splash-screen'

SplashScreen.preventAutoHideAsync()

const Layout = () => {
    const [fontsLoaded] = useFonts({
        DMBold: require('../assets/fonts/DMSans-Bold.ttf'),
        DMRegular: require('../assets/fonts/DMSans-Regular.ttf'),
        DMMedium: require('../assets/fonts/DMSans-Medium.ttf'),
    })
    
    
    const onLayoutRootView = useCallback(async () => {
        if(fontsLoaded) {
            await SplashScreen.hideAsync();
        }
    }, [fontsLoaded])

    if(!fontsLoaded) return null;
    return <Stack onLayout={onLayoutRootView} />;
}

I am trying to use the custom fonts like this:

const styles = StyleSheet.create({
  welcomeMessage: {
    fontFamily: "DMBold",
    fontSize: SIZES.xLarge,
    color: COLORS.primary,
    marginTop: 2,
  }

Please, any help would be much appreciated.

Versions: "expo": "~50.0.14" "expo-font": "~11.10.3"

2

There are 2 answers

2
Naeem Asghar On

To include custom fonts in your React Native application using Expo, you need to follow these steps:

Import Expo Font: Make sure you import expo-font in your project.

Load Fonts: Use Font.loadAsync() to load your custom fonts before rendering any UI components that use them.

Use Custom Fonts: Once the fonts are loaded, you can use them in your styles by specifying the fontFamily.

Here's how you can do it in your _layout.js file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
import React, { useState } from 'react';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';

// Function to load custom fonts
const loadFonts = async () => {
  await Font.loadAsync({
    'DMRegular': require('./path/to/DMRegular.ttf'),
    // Add more fonts if needed
  });
};

const Layout = ({ children }) => {
  const [fontsLoaded, setFontsLoaded] = useState(false);

  if (!fontsLoaded) {
    return (
      <AppLoading
        startAsync={loadFonts}
        onFinish={() => setFontsLoaded(true)}
        onError={console.warn} // Handle error if font loading fails
      />
    );
  }

  // Render children when fonts are loaded
  return (
    <React.Fragment>
      {children}
    </React.Fragment>
  );
};

export default Layout;

  1. We define a loadFonts function to load our custom fonts using Font.loadAsync().
  2. Inside the Layout component, we use useState to track whether the fonts have been loaded.
  3. If the fonts haven't loaded yet, we render AppLoading from Expo, which displays a loading screen until the fonts are loaded.
  4. Once the fonts are loaded, we render the children components.
0
Naeem Asghar On

For React.js web applications, you would typically use CSS to load custom fonts. You can either import the font files directly into your project and use the CSS @font-face rule to define the font, or you can use web font services like Google Fonts or Adobe Fonts.

Here's a basic example of using custom fonts in a React.js web application:

  1. Import the font files into your project, typically in a folder like fonts.
  2. Use CSS @font-face rule to define the font. You can do this in your CSS file or using a CSS-in-JS solution like styled-components

@font-face {
  font-family: 'YourCustomFont';
  src: url('./fonts/your-custom-font.woff2') format('woff2'),
       url('./fonts/your-custom-font.woff') format('woff');
Add additional font formats as needed.
  font-weight: normal;
  font-style: normal;
}

Apply the custom font to elements in your React components using CSS

import React from 'react';
import './App.css'; // Import your CSS file

function App() {
  return (
    <div className="App">
      <h1 style={{ fontFamily: 'YourCustomFont' }}>Hello, world!</h1>
      <p style={{ fontFamily: 'YourCustomFont' }}>This is a paragraph.</p>
    </div>
  );
}

export default App;