Last active
February 14, 2023 21:11
-
-
Save huksley/ce6b5c80c60db712ec68388a000f0615 to your computer and use it in GitHub Desktop.
Font change React component for any website https://developers.google.com/fonts/docs/developer_api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback } from "react"; | |
import useSWR from "swr"; | |
/** | |
* Allows you to choose any font from Google Fonts, overriding your CSS var --font-family | |
* Create a key at https://developers.google.com/fonts/docs/developer_api | |
*/ | |
export const FontPicker = ({ families }: { families?: string[] }) => { | |
const { data: fonts } = useSWR( | |
process.env.GOOGLE_WEBFONTS_KEY | |
? "https://www.googleapis.com/webfonts/v1/webfonts?key=" + | |
process.env.GOOGLE_WEBFONTS_KEY | |
: null, | |
key => | |
fetch(key).then( | |
res => | |
res.json() as Promise<{ | |
items: { | |
family: string; | |
}[]; | |
}> | |
) | |
); | |
const selectFont = useCallback((name?: string) => { | |
// Update CSS :root with font | |
if (name) { | |
document.documentElement.style.setProperty("--font-family", name); | |
} | |
// Load font family from Google Fonts | |
if (name) { | |
const link = document.createElement("link"); | |
link.href = `https://fonts.googleapis.com/css?family=${name.replace(" ", "+")}`; | |
link.rel = "stylesheet"; | |
document.head.appendChild(link); | |
} | |
}, []); | |
return ( | |
<select | |
disabled={!fonts && !families} | |
onClick={event => { | |
event.stopPropagation(); | |
event.preventDefault(); | |
}} | |
onChange={event => { | |
event.stopPropagation(); | |
event.preventDefault(); | |
selectFont(event.target.value); | |
}} | |
> | |
<option value="">- Select font -</option> | |
{(families ?? fonts?.items.map(item => item.family) ?? []).map(family => ( | |
<option key={family} value={family}> | |
{family} | |
</option> | |
))} | |
</select> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Provide
process.env.GOOGLE_WEBFONTS_KEY
or run as