use-simple-text-fit
v1.0.2
Published
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.
Downloads
83
Readme
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-fit
Or if you prefer yarn:
yarn add use-simple-text-fit
Usage
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 containingmin
andmax
font 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