diff --git a/src/components/MeasuredText.tsx b/src/components/MeasuredText.tsx new file mode 100644 index 0000000..bd3b52d --- /dev/null +++ b/src/components/MeasuredText.tsx @@ -0,0 +1,39 @@ +'use client'; + +import { useEffect, useRef, useState } from 'react'; +import { measureText } from '@chenglou/pretext'; + +interface MeasuredTextProps { + text: string; +} + +export default function MeasuredText({ text }: MeasuredTextProps) { + const ref = useRef(null); + const [width, setWidth] = useState(null); + + useEffect(() => { + if (!ref.current) return; + + const style = window.getComputedStyle(ref.current); + const measured = measureText(text, { + font: { + family: style.fontFamily.split(',')[0].replace(/['"]/g, ''), + size: parseFloat(style.fontSize), + weight: style.fontWeight, + }, + }); + + setWidth(measured.width); + }, [text]); + + return ( +
+ + {text} + + {width !== null && ( +

Measured width: {width.toFixed(2)}px

+ )} +
+ ); +}