@tag0/use-text-width
Version:
React hook to measure text width
58 lines (39 loc) • 1.2 kB
Markdown
[![License][license-src]][license-href]
React hook to calculate text width
```bash
npm install @tag0/use-text-width
yarn add @tag0/use-text-width
```
Run `yarn start` to view [example](src/examples/simple.tsx) on http://localhost:5000
There are 2 types of usages:
You can pass object having `text` (mandatory, string or string[] returns max one) and `font` (optional, CSS font string) properties to calculate width.
```jsx
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>
);
};
```
You can pass object having `ref` (mandatory, HTMLElement) property to calculate width.
```jsx
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>
);
};
```
[]: https://img.shields.io/badge/license-MIT-brightgreen.svg
[]: LICENSE.md