@tag0/use-text-width
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

useTextWidth

License

React hook to calculate text width

Install

npm install @tag0/use-text-width
# OR
yarn add @tag0/use-text-width

Usage

Run yarn start to view example on http://localhost:5000

There are 2 types of usages:

1. text & font

You can pass object having text (mandatory, string or string[] returns max one) and font (optional, CSS font string) properties to calculate width.

import { useTextWidth } from '@tag0/use-text-width';

const App = () => {
  const width = useTextWidth({ text: 'Hello world!', font: '20px Times' });

  return (
    <p>Hello world! text width: {width}px</p>
  );
};

2. ref

You can pass object having ref (mandatory, HTMLElement) property to calculate width.

import { useTextWidth } from '@tag0/use-text-width';

const App = () => {
  const ref = useRef();
  const width = useTextWidth({ ref });

  return (
    <p ref={ref} style={{ fontSize: '16pt', fontWeight: 'bold' }}>
      lorem ipsum! text width: {width}px
    </p>
  );
};

Dependents (1)

Package Sidebar

Install

npm i @tag0/use-text-width

Weekly Downloads

1,178

Version

1.2.0

License

MIT

Unpacked Size

21.9 kB

Total Files

10

Last publish

Collaborators

  • erhangundogan