React hook that iteratively adjusts the font size so that text will fit in a div.
scrollHeight
and offsetHeight
ResizeObserver
)npm install --save use-fit-text
import React from "react";
import useFitText from "use-fit-text";
function Example() {
const { fontSize, ref } = useFitText();
return (
<div ref={ref} style={{ fontSize, height: 40, width: 100 }}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
);
}
/examples
folderReturns an object with the following properties:
fontSize
(string
) - the font size as a string (CSS percent) to be passed as the fontSize
property of the style
prop of the div
ref
(React.MutableRefObject<HTMLDivElement>
) - the ref to be passed to the ref
attribute of the div
options
(optional) - an object with the following optional properties:
maxFontSize
(number
, default: 100
) - maximum font size in percentminFontSize
(number
, default: 20
) - minimum font size in percentonFinish
((fontSize: number) => void
, default: undefined
) - function that is called when resizing finishes. The final fontSize is passed to the function as an argument.onStart
(() => void
, default: undefined
) - function that is called when resizing startsresolution
(number
, default: 5
) - font size resolution to adjust to in percentjustify-content: flex-end;
? This appears to be a bug with Flexbox. Try using CSS Grid or margin-top: auto;
minFontSize
is set larger than the fontSize
value needed to fit the text in the div. Log an error to the console in this case.onStart
and onFinish
callbacksTOptions
TypeScript type/// <reference types="next" />
in dist/index.d.ts
useLayoutEffect
warning for server renderResizeObserver
to always recalculate on container resizerecalcOnResize
optionuseLayoutEffect
instead of useEffect
to avoid flashingrecalcOnResize
and other optionsAuthor: saltycrane
Demo: https://saltycrane.github.io/use-fit-text/
Source Code: https://github.com/saltycrane/use-fit-text
#react #reactjs #javascript