calculate-text-width

Function that calculates width of typed text. Auto calculate input width.

MIT License

Downloads
1.5K
Stars
4
Committers
2

Calculate Text Width

Function that calculates width of typed text

Code Sandbox Demo

How to use

import calculateTextWidth from "calculate-text-width";

/*
 requires two props "value" and "font"
  - defaultFont: normal 500 14px sans-serif 
 */
const calculatedWidth = calculateTextWidth('calculate my width', 'normal 500 14px sans-serif')
console.log(calculatedWidth) // 114.37890625

How to use with React

import React, { useState, useMemo } from "react"
import calculateTextWidth from "calculate-text-width"

export default () => {
  const [value, setValue] = useState("change me")

  return (
    <>
      <h1>Calcule Text Width</h1>
      <input
        style={{
          width: `${calculateTextWidth(value)}px`,
          font: "normal 500 14px sans-serif"
        }}
        value={value}
        type="text"
        onChange={evt => setValue(evt.target.value)}
      />
    </>
  )
}

Thank you

Yusuf Özlü

Package Rankings
Top 11.49% on Npmjs.org
Badges
Extracted from project README
npm version