I am making masonry grid gallery in React and I have trouble getting image height after load and before resizing it with grid. I have onLoad
handler on img
but there I get only already resized image height where it should be original, to use it to calculate number of row spans. I am aware it could be pure css problem, but I don't know how to solve it.
Here is my useEffect
:
useEffect(() => {
if (imageRef.current && !loading) {
const height = imageRef.current.clientHeight;
console.log('height', height);
const spansCount = Math.ceil(height / 10 + 1);
setSpansCount(spansCount);
}
}, [imageRef.current, loading]);
And here is my render
:
return (
<div
{...rest}
className={styles.gallery__item}
style={{ gridRowEnd: `span ${spansCount}` }}
>
<img
src={image.previewURL}
ref={imageRef}
className={styles.gallery__img}
alt={image.tags}
onLoad={handleLoad}
/>
<Placeholder
ref={loaderRef}
style={loading ? { display: 'block' } : { display: 'none' }}
/>
</div>
Here is my non working Codesandbox .
And here is working Codesandbox with react-load-image
package, but I am not sure why this is working and the first one isn't.
I just needed to change this css on image:
.gallery__img {
width: 100%;
height: auto; // not 100%
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.