Skip to content

Instantly share code, notes, and snippets.

@huksley
Last active February 14, 2023 21:11
Show Gist options
  • Save huksley/ce6b5c80c60db712ec68388a000f0615 to your computer and use it in GitHub Desktop.
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
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>
);
};
@huksley
Copy link
Author

huksley commented Feb 14, 2023

Provide process.env.GOOGLE_WEBFONTS_KEY or run as

<FontPicker
  families={[
    "Ubuntu",
    "Roboto",
    "Open Sans",
    "Lato",
    "Montserrat",
    "Raleway",
    "Oswald",
    "Lobster",
    "Pacifico",
    "Indie Flower",
    "Dancing Script",
    "Inter"
  ]}
/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment