I am trying to use the "next" way of adding fonts. However I feel like the way they explain it seems extremely complicated just to preload a font.
I tried to export a function creating the font and then using the variable tag to create a css var. This doesnt work, I have imported the font into my page.js file. Then I exported a const function creating the font with this variable;
import { Oxygen } from "next/font/google";
export const oxygen = Oxygen({
display: 'swap',
variable: '--font-oxygen',
subsets: ['latin'],
})
Then tried to use it in the linked css style sheet setting the font family to the exact var using;
font-family: var(--font-oxygen);
I am trying to learn Nextjs and this is just putting me off. It wont work, I dont want to set the class name of my html attributes to the font class name either unless I am doing it all wrong.
2
Answers
If this is a font used in your entire application you can import the font in
index.js
(when using Pages Router) or in thelayout.js
in yourapp
folder (when using App Router). You don’t have to add it to your CSS.Then add
classname={oxygen.className}
For Pages Router example;
You are supposed to use the font’s
font.variable
method, not thefont.className
method.Now, you can add that variable to any css class:
Note: This works with app router, but I am unsure if it works for page router.
This should preload the font as well, which means that it does not flicker when the page loads.