Skip to content

Instantly share code, notes, and snippets.

@benvium
Created December 15, 2023 14:42
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 benvium/9007174dcd27848ec6f36f947063c996 to your computer and use it in GitHub Desktop.
Save benvium/9007174dcd27848ec6f36f947063c996 to your computer and use it in GitHub Desktop.
React Native <Text/> wrapper for accessibility font sizes with automatically-calculated maximum font size
// Maximum font size. Note For WCAG we should support at least 200% default font scale
const MAXIMUM_FONT_SIZE = 32;
/**
* Use to calculate a maxFontSizeMultiplier for Text components to ensure
* the text size doesn't go beyond MAXIMUM_FONT_SIZE.
* Pass the style or a fixed number.
* If the original size is already bigger than 32, then the size will be unchanged.
*/
export function getMaxFontSizeMultiplier(params: number | StyleProp<TextStyle>) {
let fontSize = typeof params === 'number' ? params : undefined;
// Grab the fontSize prop from the style
if (typeof params === 'object') {
fontSize = StyleSheet.flatten(params)?.fontSize;
}
if (fontSize === undefined) return 1;
// calculate multiplier to make max font = MAXIMUM_FONT_SIZE
return Math.max(MAXIMUM_FONT_SIZE / fontSize, 1);
}
const TextA11y_ = (props: TextProps) => {
const {maxFontSizeMultiplier, ...otherProps} = props;
return (
<Text
{...otherProps}
maxFontSizeMultiplier={maxFontSizeMultiplier ?? (props.style ? getMaxFontSizeMultiplier(props.style) : undefined)}
>
{props.children}
</Text>
);
};
export const TextA11y = memo(TextA11y_);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment