React hook used to fit text in a div
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
folderuseFitText(options)
Returns 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:
logLevel
(string
, default: info
) - one of debug
, info
, warn
, error
, or none
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 = 20
without fitting text" message in the console mean?
This means use-fit-text
was not able to fit the text using the minFontSize
setting of 20. To ensure the text fits, set minFontSize
to a smaller value.minFontSize
is set larger than the fontSize
value needed to fit the text in the div. Log a message to the console in this case.logLevel
option to control what is logged to the consoleonStart
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 options