Hosted Fonts and getBoundingClientRect
When using hosted fonts and getBoundingClientRect
to get the dimensions or positioning of a text element, you may find incorrect values being returned. This is because the browser doesn’t know the font’s metrics until its been downloaded and parsed.
useEffect(() => {
// returns an incorrect value if the font hasn't been downloaded yet
const x = element.current.getBoundingClientRect().x;
});
Save yourself the hair pulling I just went though by using by using the FontFaceSet ready
method to check if the font has been loaded before using getBoundingClientRect
.
const [fontLoaded, setFontLoaded] = useState(false);
useEffect(() => {
document.fonts.ready.then(() => {
setFontLoaded(true);
});
});
useEffect(() => {
const x = element.current.getBoundingClientRect().x;
}, [fontLoaded]);