Skip to content

Instantly share code, notes, and snippets.

@reichert621
Last active February 8, 2024 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reichert621/2e492a11a3e79a1c35e4c026d3ab31d0 to your computer and use it in GitHub Desktop.
Save reichert621/2e492a11a3e79a1c35e4c026d3ab31d0 to your computer and use it in GitHub Desktop.
Quickly inject a Google font into your Next app via "font" query parameter
import {useRouter} from 'next/router';
import {useEffect} from 'react';
// Small hack to inject a Google font into the webpage
function appendCustomFont(font: string) {
if (typeof document === 'undefined') {
return console.warn(
'`window.document` unavailable: cannot append custom font.'
);
}
const el = document.createElement('link');
const uriFontFamily = font.split(' ').join('+');
const cssFontFamily = font.split('+').join(' ');
el.id = '__custom-font-loader';
el.rel = 'stylesheet';
el.href = `https://fonts.googleapis.com/css2?family=${uriFontFamily}:wght@200;300;400;500;600;700;800&display=swap`;
const originalFontFamily = document.body.style.fontFamily;
document.head.append(el);
document.body.style.fontFamily = cssFontFamily;
// Cleanup function to remove injected code above
return () => {
document.body.style.fontFamily = originalFontFamily;
el.parentElement?.removeChild(el);
};
}
export function useCustomizableFont() {
const router = useRouter();
useEffect(() => {
if (!router.isReady) {
return;
}
const font = router.query.font as string;
if (!font) {
return;
}
const undo = appendCustomFont(font);
return undo;
}, [router]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment