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);
}, []);