1.0.2 • Published 2 years ago
use-simple-text-fit v1.0.2
useTextFit & fitText
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.
Table of Contents
Installation
Install the package via npm:
npm install use-simple-text-fitOr if you prefer yarn:
yarn add use-simple-text-fitUsage
useTextFit
A React Hook to automatically adjust the font size of an HTML element so that it fits its container.
Syntax
const [ref, fit] = useTextFit(options?, deps?)Parameters
options: An object containingminandmaxfont sizes (optional).deps: React dependency array for the effect (optional).
Return Value
ref: A React ref to be attached to the HTML element.fit: A function that can be called to manually trigger a resize.
fitText
A helper function to manually adjust the font size of an HTML element so that it fits its container.
Syntax
fitText(element, min, max)Parameters
element: The HTML element to adjust.min: Minimum font size.max: Maximum font size.
Examples
Using useTextFit
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>
);
}Using fitText
import { fitText } from 'use-simple-text-fit';
const element = document.querySelector('.my-element');
fitText(element, 10, 50);License
MIT