0

I am able to use inline styling to use an imported font in an Expo project. However, for the sake of tidiness, I wanted to put all of my styling into a separate file from the code. I am using the react-native StyleSheet library for my styling. It seems that as soon as I move the style with the custom font into another file, the font can no longer be accessed by the StyleSheet.

I have tried importing the font with npx react-native-asset, the useFonts hook, and the loadAsync() function, and all give the same result. I tried the solution of waiting for the fonts to load before rendering the components (suggested here), but had the same result again.

I understand I could make the StyleSheet within the component file, but I want it to be reusable across multiple components.

styles.tsx

import { StyleSheet } from "react-native";


export default StyleSheet.create({
    customText: {
        fontFamily: "SpicyRice",
        color: "red",
    },
});

MyComponent.tsx

import styles from "./styles";

export default (
    <View>
        <Text style={{fontFamily: "SpicyRice"}}>
            THIS IS WORKING WITH THE CUSTOM FONT.
        </Text>

        <Text style={styles.customText}>
            THIS IS NOT USING THE CUSTOM FONT.
            HOWEVER, IT IS RED, SO I KNOW IT IS USING THE STYLESHEET.
        </Text>
    </View>
);

react-native.config.js

module.exports = {
    project: {
        ios: {},
        android: {},
    },
    assets: ["./fonts"],
};

1 Answers1

0

I am not sure if this is the solution you are looking for but here is what is working for me.

In my App.js:

import { useCallback } from "react"
import { useFonts } from "expo-font"
import * as SplashScreen from "expo-splash-screen"

const App = () => {

    // FONTS
    const [fontsLoaded, fontError] = useFonts({
        PoppinsRegular: require('./assets/fonts/Poppins-Regular.ttf'),
        PoppinsBold: require('./assets/fonts/Poppins-Bold.ttf'),
        RubikIso: require('./assets/fonts/RubikIso-Regular.ttf'),
    })

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

    if (!fontsLoaded && !fontError) return null

    return (

        <SafeAreaView style={styles.container}>
            <StackComponent onLayout={onLayoutRootView} />
        </SafeAreaView>
    )
}

This way I am making sure the custom fonts can be used across my entire app.

Then I created a theme.js file inside a constants folder where I define which font to use for each situation, I also have stuff like colors and sizes in this same file.

const FONT = {
      regular: "PoppinsRegular",
      bold: "PoppinsBold",
      special: "RubikIso",
    }

export { COLORS, FONT, SIZES, SHADOWS }

And then from any stylesheet I can just import these constants and use the fonts I want by doing something like:

title: {
fontFamily: FONT.regular,
color: COLORS.primary
}