react-use-text-measurer

Synchronously measure text size in an offscreen <canvas /> via react hook.

Usage no npm install needed!

<script type="module">
  import reactUseTextMeasurer from 'https://cdn.skypack.dev/react-use-text-measurer';
</script>

README

react-use-text-measurer

A hook for synchronously measuring text in react applications using an offscreen <canvas /> along with CanvasRenderingContext2D.measureText() to make measurements.

const YourComponent = (props) => {
  const measureTitle = useTextMeasurer("600 24px 'Source Sans Pro'");

  return (
    <>
      <h1>{props.title}</h1>
      <div>👆 {measureTitle(props.title)}px</div>
    </>
  )
}

Installation

# with npm
npm install react-use-text-measurer

# with 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 <canvas /> element, and exposing context for useTextMeasurer. It accepts all the arguments the native <canvas /> element does and passes them through, so you can override things like style.

import {TextMeasurementProvider} from 'react-use-text-measurer';

export function YourApp() {
  return (
    <TextMeasurementProvider>
      <YourApp>
        {/** ... */}
      </YourApp>
    </TextMeasurementProvider>
  )
}

Then, use the hook to create a measuring function by providing a CSS font specifier:

const YourComponent = (props) => {
  const measureTitle = useTextMeasurer("600 24px 'Source Sans Pro'");

  return (
    <>
      <h1>{props.title}</h1>
      <div>👆 {measureTitle(props.title)}px</div>
    </>
  )
}

Why?

For example, to build a windowed list without DOM measuring.