Created
December 15, 2023 14:42
-
-
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
This file contains hidden or 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
// 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