Synchronously measure text size in an offscreen <canvas /> via react hook.
npm install react-use-text-measurerA hook for synchronously measuring text in react applications using an offscreen along with CanvasRenderingContext2D.measureText() to make measurements.
``tsx
const YourComponent = (props) => {
const measureTitle = useTextMeasurer("600 24px 'Source Sans Pro'");
return (
<>
Installation
`
with npm
npm install react-use-text-measurerwith yarn
yarn add react-use-text-measurer
`Usage
First, wrap your app (or any subtree where you'd like to use useTextMeasurer) in the provider: TextMeasurementProvider which is repsonsible for caching measurements, managing the hidden element, and exposing context for useTextMeasurer. It accepts all the arguments the native element does and passes them through, so you can override things like style.`tsx
import {TextMeasurementProvider} from 'react-use-text-measurer';export function YourApp() {
return (
{/* ... /}
)
}
`Then, use the hook to create a measuring function by providing a CSS font specifier:
`tsx
const YourComponent = (props) => {
const measureTitle = useTextMeasurer("600 24px 'Source Sans Pro'"); return (
<>
{props.title}
👆 {measureTitle(props.title)}px
>
)
}
``