A very simple React Hook and helper function to dynamically adjust the font size of an HTML element to fit its container. It uses a binary search algorithm for efficiency. Works right out of the box.
Install the package via npm:
npm install use-simple-text-fitOr if you prefer yarn:
yarn add use-simple-text-fitA React Hook to automatically adjust the font size of an HTML element so that it fits its container.
const [ref, fit] = useTextFit(options?, deps?)options: An object containingminandmaxfont sizes (optional).deps: React dependency array for the effect (optional).
ref: A React ref to be attached to the HTML element.fit: A function that can be called to manually trigger a resize.
A helper function to manually adjust the font size of an HTML element so that it fits its container.
fitText(element, min, max)element: The HTML element to adjust.min: Minimum font size.max: Maximum font size.
import { useTextFit } from 'use-simple-text-fit';
const MyComponent = () => {
const [ref, fit] = useTextFit();
// Use fit to trigger a resize manually, or pass a dependency array to useTextFit
return (
<div ref={ref}>
Text to fit
</div>
);
}import { fitText } from 'use-simple-text-fit';
const element = document.querySelector('.my-element');
fitText(element, 10, 50);MIT