feat: add client component demonstrating Pretext text measurement
This commit is contained in:
@@ -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<HTMLSpanElement>(null);
|
||||
const [width, setWidth] = useState<number | null>(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 (
|
||||
<div>
|
||||
<span ref={ref} style={{ fontSize: '2rem', fontWeight: 700 }}>
|
||||
{text}
|
||||
</span>
|
||||
{width !== null && (
|
||||
<p style={{ color: 'dimgray' }}>Measured width: {width.toFixed(2)}px</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user