react-use-text-measurer
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

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.

Package Sidebar

Install

npm i react-use-text-measurer

Weekly Downloads

131

Version

1.0.3

License

ISC

Unpacked Size

18.3 kB

Total Files

7

Last publish

Collaborators

  • the_ruther4d