Skip to content

Instantly share code, notes, and snippets.

@ansh
Created December 14, 2022 13:17
Show Gist options
  • Save ansh/37a603355551f7b63f9adf93d36d7e27 to your computer and use it in GitHub Desktop.
Save ansh/37a603355551f7b63f9adf93d36d7e27 to your computer and use it in GitHub Desktop.
Map fontWeight to fontFamily for custom fonts in React Native with pure TypeScript
// This is a little code snippet I found useful for adding custom fonts to your React Native / Expo project.
// The essential idea is that we map fontWeight to fontFamily via a simple function and some TypeScript magic. We can also make it faster by wrapping the function in a useMemo hook
// Here is the mappings of fontWeight to fontFamily for your custom font
export const Poppins = {
"100": "Poppins_100Thin",
"200": "Poppins_200ExtraLight",
"300": "Poppins_300Light",
"400": "Poppins_400Regular",
"500": "Poppins_500Medium",
"600": "Poppins_600SemiBold",
"700": "Poppins_700Bold",
"800": "Poppins_800ExtraBold",
"900": "Poppins_900Black",
"thin": "Poppins_100Thin",
"extraLight": "Poppins_200ExtraLight",
"light": "Poppins_300Light",
"regular": "Poppins_400Regular",
"medium": "Poppins_500Medium",
"semiBold": "Poppins_600SemiBold",
"bold": "Poppins_700Bold",
"extraBold": "Poppins_800ExtraBold",
"black": "Poppins_900Black",
} as const;
// Put this function inside your Text component to convert fontWeight to fontFamily easily
const fontFamily = useMemo(() => {
if (!style) {
return Poppins.regular;
}
const flattenedStyle = StyleSheet.flatten(style);
const fontWeight = flattenedStyle.fontWeight;
const poppinsFontFamily = Poppins[fontWeight as keyof typeof Poppins];
return poppinsFontFamily || Poppins.regular;
}, [style])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment