Next.js
Next.js Image 태그 height auto로 사용하기 (update 13 version)
Kir93
2023. 8. 4. 16:11
728x90
반응형
이 글은 next v13.4를 기반으로 작성되었습니다.
Next 12 버전을 기반으로 height auto Image태그를 작성한 지 오래되지 않아 13 버전에서는 더욱 간단하게 사용할 수 있게 되어 소개하려고 한다.
// AutoHeightImage.tsx
import Image, { ImageProps } from 'next/image';
interface IAutoHeightImage extends Omit<ImageProps, 'width'> {
width?: string | number;
alt: string;
}
const AutoHeightImage = ({ width = '100%', alt = '', ...props }: IAutoHeightImage) => (
<Image
{...props}
width={0}
height={0}
sizes="100vw"
alt={alt}
style={{ ...props?.style, width, height: 'auto' }}
/>
);
export default AutoHeightImage;
// page.tsx
import AutoHeightImage from '@/components/AutoHeightImage';
export default function Home() {
return (
<div>
<h2>AutoHeightImage Test</h2>
<AutoHeightImage src="/test.jpeg" alt="test image" />
</div>
);
}
이전 12 버전과 동일하게 외부에서 불러오는 이미지의 경우 width, height가 필수 값인 것은 동일하지만 이제는 span아래에 생성되는 형식이 아니라 온전히 하나의 태그로 생성되기 때문에 좀 더 심플해졌다.
width와 height값은 사실 크게 중요하지 않지만 0, 0으로 하는 것이 이미지 호출 뒤에 이미지의 사이즈가 변경될 수 있는 현상을 없앨 수 있기 때문에 설정했다.
가장 중요한 것은 sizes값으로 해당 값을 충분히 크게 설정하지 않을 경우 이미지를 최적화하는 과정에서 작은 이미지로 인식해 이미지의 화질이 저하되는 문제가 있을 수 있다.
그리고 원래라면 styled components를 활용해 스타일을 줬겠지만 이제 Next Image 자체적으로 style을 받을 수 있기 때문에 자체적으로 style을 주었다.
원래는 숫자만 입력 가능했던 것과 달리 이제 간편하게 %, px, rem 등의 단위를 이용해 사용할 수 있다.
반응형