Skip to content

Latest commit

 

History

History
62 lines (42 loc) · 1.39 KB

README.md

File metadata and controls

62 lines (42 loc) · 1.39 KB

Calculate Text Width

Function that calculates width of typed text

npm version npm download

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ü