Function that calculates width of typed text
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
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