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.
You are supposed to use the font's font.variable
method, not the font.className
method.
import { Oxygen } from 'next/font/google'
const oxygen = Oxygen({
display: 'swap',
variable: '--font-oxygen',
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={oxygen.variable}> // USE .variable, NOT .className
<Component {...pageProps} />
</main>
)
}
Now, you can add that variable to any css class:
.text {
font-family: var(--font-oxygen);
}
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.