Home > Net >  How to use a custom font in react native with nativewind?
How to use a custom font in react native with nativewind?

Time:12-16

I'm a newbie in React-Native and I have an issue with fonts adding, I'm trying to load a custom font from .otf file, but I have an error:

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

- If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.

- If this is a custom font, be sure to load it with Font.loadAsync.

I have tried to use the Font.loadAsync but get this error in any case.

My code right now:

Home.js

import {
  View,
  Text
} from "react-native";
import React from "react";

// State
import {
  useState
} from "react";

// Fonts
import AppLoading from "expo-app-loading";
import useFonts from "../hooks/useFonts";

const Home = () => {
  const [IsReady, SetIsReady] = useState(false);

  const LoadFonts = async() => {
    await useFonts();
  };

  if (!IsReady)
    return ( <
      AppLoading startAsync = {
        LoadFonts
      }
      onFinish = {
        () => SetIsReady(true)
      }
      one rror = {
        () => {}
      } >
      < /AppLoading>
    );

  return ( <
    View className = "bg-mainRed flex-1 justify-center items-center" >
    <
    Text className = "font-Musketeer text-5xl" > King 's Dungeon</Text> <
    /View>
  );
};

export default Home;

useFonts.js

import * as Font from "expo-font";

export default useFonts = async () =>
  await Font.loadAsync({
    Musketeer: require("../assets/fonts/Pixel-Musketeer.otf"),
  });

Tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./App.{js,jsx,ts,tsx}",
    "./screens/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    colors: {
      mainRed: "#3B111D",
      grey: "#564950",
      darkGreen: "#86978F",
      green: "#BEDDA4",
      brightGreen: "#E4FABD",
    },
    extend: {
      fontFamily: {
        Musketeer: ["Pixel-Musketeer"],
      },
    },
  },
  plugins: [],
};

What should I remove or add in order to load this font?

CodePudding user response:

use/make theme.js where you save as constants so that you can use it on whole app:

export const FONTFAMILY = {
    musketeer: {fontFamily: 'Musketeer'},
}

and then in you main App.js

import { useFonts } from 'expo-font';
import { FONTFAMILY } from './theme.js';

export default function App() {

  const [fontsLoaded] = useFonts({
    'Musketeer': require("../assets/fonts/Pixel-Musketeer.otf"),
  });

  if(!fontsLoaded) return null;

  return (
    <Text style={{...FONTFAMILY.musketeer}}>used fonts here</Text
  );
}

CodePudding user response:

If not already created, create a config file at the root of the project named react-native.config.js. Proceed by adding the following code inside module.exports:

  • Related