I had the same issue too: I wanted to use Image
from next/image in a masonry ImageList
from MUI...
Anyway, this is the trick I used to get the size of my image and so to handle the size of the container:
import React, { FC, useState } from 'react';
import styled from 'styled-components';
import Image from 'next/image';
interface Props {
src: string;
}
export const MasonryItem: FC<Props> = ({ src }) => {
const [paddingTop, setPaddingTop] = useState('0');
return (
<Container style={{ paddingTop }}>
<Image
src={src}
layout="fill"
objectFit="contain"
onLoad={({ target }) => {
const { naturalWidth, naturalHeight } = target as HTMLImageElement;
setPaddingTop(`calc(100% / (${naturalWidth} / ${naturalHeight})`);
}}
/>
</Container>
);
};
const Container = styled.div`
position: relative;
`;
The idea: get size of image when it's loaded, calc the ratio and use it to make the container fill the require space with padding-top. This way no matter your image size the container will be fit to it.
Remark, I didn't use width or height on the container because I didn't need it with my project, but maybe you will have to set one of both for your project.
As I'm still beginning with React & NextJS & typescript, maybe the solution can be prettier, if someone have an idea to improve it I'll be pleased to read it!