Reputation: 634
I have an image which I want to absolute position within a parent div, but I don't know the size of the parent div until it renders.
In React, how can I get the width of the container before rendering the image?
Any hack solution is allowed as long as it works.
Bonus for having it respond to window size changes.
Upvotes: 0
Views: 1472
Reputation: 84902
You can use a ref to get the div element, and then check its size in an effect. You'll probably set state at that point, thus rendering again now that you know the size.
const Example = () => {
const [width, setWidth] = useState(null);
useEffect(() => {
setWidth(containerRef.current.clientWidth);
}, []);
const containerRef = useRef(null);
return (
<div ref={containerRef}>
{width !== null && (
// render an image, using the width however you need to
)}
</div>
)
}
Depending on what you're doing with this width, you may see a flicker due to it rendering once without the image, and once with. If that's the case, you can eliminate the flicker by switching from useEffect
to useLayoutEffect
. This will make the 2nd render be synchronous, and thus the user will not get a chance to see the 1st render.
Bonus for having it respond to window size changes.
You can listen to window resize like this:
useEffect(() => {
const handleResize = () => {
setWidth(containerRef.current.clientWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
Upvotes: 2