🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

react-use-text-measurer

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-use-text-measurer

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

1.0.3
latest
npm
Version published
Weekly downloads
268
-12.99%
Maintainers
1
Weekly downloads
 
Created
Source

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.

Keywords

react

FAQs

Package last updated on 01 Mar 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts