I’m trying to determin the width of a 1 char element defined simply as :
<div ref={refBBFS} style={{width:"1ch",fontFamily:'some monospace font'}}>X</div>
[ using nextjs 13.1.1 , reactjs 18.2.0, chrome 80.0.3987.132]
window.getComputedStyle(…).getPropertyValue(‘width’) seems to return the wrong value on chrome. ( my code works on firefox ).
its currently placed in a useEffect defined in my root element , and its executed for every render (i.e. using “,[]” ).
the value does not match what is shown in the devtools , in both the graphical view of the element, and in its computed “width” variable.
specifically, I’m getting a value of 8px for font size 16 (medium) , 6px for size 12 and so on, while chrome dev tools shows a value of 9.63281 ( and firefox shows 10.1833).
It seems to me like i’m getting a default/initial value, before some calculation has occured.
I have also executed the call to getComputedStyle(…).getPropertyValue on every window.resize event,
and when its executed on a resize event I get the expected value.
(all values derived on the resize events are exactly the same, since the resize event does not change the computed value of my element. but they differ from the initial value received after page load).
I can also share that when I change my code, and trigger online rebuild of nextjs,
the folowing render/execution gets the correct value.
but otherwise, simple serving of the page and refreshing (using f5) return the wrong value.
its as if i’m executing the cal to window.getComputedStyle(…).getPropertyValue(‘width’) to early. but I don’t understand how and why this behaves differently on firefox.
I tried working around the problem by skipping the first render, and by explicitly triggering the resize event on the first render, but the error persisted.
example code
export default function MyApp({ Component, pageProps }: AppPropsWithLayout)
{
const refBBFS = useRef(null);
useEffect(() =>
{
const BaseWidthPx = window.getComputedStyle(refBBFS.current).getPropertyValue('width');
const BaseFSPx = window.getComputedStyle(refBBFS.current).getPropertyValue('font-size');
console.log('my app effect',BaseWidthPx,BaseFSPx);
// add resize event handler
function HandleResolutionChange()
{
console.log('** executing resolution change ** ',window.getComputedStyle(refBBFS.current).getPropertyValue('width'),window.getComputedStyle(refBBFS.current).getPropertyValue('font-size'));
}
window.addEventListener('resize', HandleResolutionChange);
HandleResolutionChange();
return () =>
{
window.removeEventListener('resize', HandleResolutionChange);
}
}, []);
return (<>
<div ref={refBBFS} style={{width:"1ch",fontFamily:'...'}}>X</div>
</>);
}
2
It seems that the error does not reproduce on edge, or newer versions of chrome, so It may be specific to some older versions of chrome and thus not a major issue at the moment