Home > front end >  How to change font family only for one element - nextjs
How to change font family only for one element - nextjs

Time:10-24

My project has a global font. but for only one element I get font families randomly from a hosted url. example:

https://minio.kadoxa.com/file/fonts/Parnian.ttf

my page is a CSR.

now How I can use this font for my element?

CodePudding user response:

You can dynamically load fonts with Javascript.

const fontFace = new FontFace(newFontName, `url(${newFontUrl})`);
fontFace.load().then((loadedFace: FontFace) => {
  document.fonts.add(loadedFace);
  setFontFamily(newFontName);
};

Here is an example dynamically loading Google Fonts in NextJS.

enter image description here

import { useState } from 'react';
import type { NextPage } from 'next';
import * as font from 'random-google-font';

const Home: NextPage = () => {
  const [fontFamily, setFontFamily] = useState('cursive');

  const updateFont = async () => {
    const response = await font.get();
    if (response.length < 1) return;
    const newFontName = response[0].local[0].substring(
      1,
      response[0].local[0].length - 1
    );
    const newFontUrl = response[0].url.ttf;
    const fontFace = new FontFace(newFontName, `url(${newFontUrl})`);
    const loadedFace = await fontFace.load();
    document.fonts.add(loadedFace);
    setFontFamily(newFontName);
  };

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        gap: '1em',
      }}
    >
      <span style={{ fontFamily }}>Hello S.M_Emamian!</span>
      <div style={{ cursor: 'pointer' }} onClick={updateFont}>
                   
  • Related