この記事では Next.js, React を使ったWebのプロジェクトにAdobeFontを読み込ませる方法を解説しています。
AdobeFonts.tsx を作成します。
'use client';
import { useEffect } from 'react';
export default function AdobeFonts() {
useEffect(() => {
const kitId = 'あなたのKey';
const config = { kitId, scriptTimeout: 3000, async: true } as const;
const h = document.documentElement;
const t = window.setTimeout(() => {
h.className = h.className.replace(/\bwf-loading\b/g, '') + ' wf-inactive';
}, config.scriptTimeout);
const tk = document.createElement('script');
let f = false;
h.classList.add('wf-loading');
tk.src = `https://use.typekit.net/${config.kitId}.js`;
tk.async = true;
const onload = () => {
if (f) return;
f = true;
window.clearTimeout(t);
try {
// @ts-ignore
window.Typekit?.load({ async: config.async });
} catch (e) {
// no-op
}
};
tk.onload = onload;
// 古いブラウザ互換(readyState)
// @ts-ignore
tk.onreadystatechange = function () {
// @ts-ignore
const a = this.readyState;
if (f || (a && a !== 'complete' && a !== 'loaded')) return;
onload();
};
document.head.appendChild(tk);
return () => {
window.clearTimeout(t);
};
}, []);
return null;
}
これをLayout.tsxのbodyで呼び出しましょう。
私はJoyUIを使ってるので以下の感じで埋め込みました。
import { CssVarsProvider } from '@mui/joy/styles';
import './globals.css';
import Script from 'next/script';
import AdobeFonts from './components/AdobeFonts';
export const metadata = {
title: 'coiai',
description: 'XR, Web, システム開発, DX 想像できることを美しく実現',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="ja">
<head>
</head>
<body>
<AdobeFonts />
<CssVarsProvider defaultMode="light">
{children}
</CssVarsProvider>
</body>
</html>
);
}
最後にFontFamilyの設定をします。
Global.cssにたとえば以下のように書けば反映されるはずです。
html, body {
font-family: "ryo-gothic-plusn", -apple-system, sans-serif;
font-weight: 400;
font-style: normal;
}
ぜひ参考にしてみてね!
coiai