I'm using a Portal component to create a portal and add it to the document.
Some component (a tooltip, in my actual use case) is a child of the portal and needs to read its width (in my case, to check if the tooltip will be outside the window, and reposition it if necessary), and then re-render itself using useLayoutEffect
.
My issue is that the callback of useLayoutEffect is called before the element has been rendered, so when I do something like getBoundingClientRect()
, the width is still 0. If I move the component outside of the portal then it works correctly.
https://codesandbox.io/s/divine-snowflake-071dbw
Relevant parts:
const Portal = ({ children }) => {
const [container] = useState(() => {
const el = document.createElement("div");
return el;
});
useEffect(() => {
document.body.appendChild(container);
return () => {
document.body.removeChild(container);
};
}, [container]);
return createPortal(children, container);
};
const MyComponent = ({ name }) => {
const ref = useRef(null);
useLayoutEffect(() => {
if (ref.current) {
const rect = ref.current.getBoundingClientRect();
// For the component inside the portal,
// the width/height/etc is all 0
console.log("rect of", name, rect.width);
}
}, [name]);
return <div ref={ref}>{name}</div>;
};
const App = () => {
return (
<>
<Portal>
<MyComponent name="component inside portal" />
</Portal>
<MyComponent name="outside" />
</>
);
}
Logs
rect of component inside portal 0
rect of outside 770