You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
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.2
npmnpm
Version published
Weekly downloads
305
7.77%
Maintainers
1
Weekly downloads
 
Created
Source

react-use-text-measurer

A hook for synchronously measuring text in react applications without DOM-thrashing! Uses an offscreen <canvas /> along with CanvasRenderingContext2D.measureText() to make measurements.

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'");
  const titleWidth = measureTitle(props.title);

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

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