Next.js에서 무한스크롤 & Masonry Layout 구현

오민준·2023년 3월 22일
0

TIL

목록 보기
5/9

1. egjs-infinitegrid 사용 이유

  • 우리 프로젝트에 필요한 무한 스크롤을 기본적으로 제공해준다.
  • 프로젝트에 사용하려 한 Masonry Layout과 같은 다양한 Layout을 제공한다.

2. 사용한 라이브러리

// 이번 task에서 사용한 라이브러리
npm i @egjs/infinitegrid

// class 형태로 개발한 react code의 오류를 없애준다.
npm i prop-types

// width크기를 고정하고 height를 불러오기 위해 사용
npm i styled-components

3. 겪었던 어려움

  • Next.js의 Image가 흉악하다는 이야기는 들었지만 생각보다 더 흉악했다.
    • 첫 번째로 Next.js Image는 명시적으로 width와 height를 제공해야 렌더링이 된다.
    • 나의 경우 width를 기준으로 height를 auto 값으로 사용하기를 원했으나 auto는 명시적이지 않은 크기이므로 사용이 불가능 했다.
    • 그래서, AutoHeightImage.tsx 라는 컴포넌트를 분리해 가로 길이를 화면 크기에 비례한 크기로 유지하고 세로 길이를 가로에 비례한 크기로 만들었다.
    • 이 과정에서 styled component를 쓰는 방법 또한 공부하였다.
// AutoHeightImage.tsx

import React from "react";
import Image, { ImageProps } from "next/legacy/image";

import { AutoHeightImageWrapper } from "./AutoHeightImage.styles";

const AutoHeightImage = ({ ...props }: ImageProps): React.ReactElement => (
  <AutoHeightImageWrapper>
    <Image priority layout="fill" className="autoImage" {...props} />
  </AutoHeightImageWrapper>
);

export default AutoHeightImage;
// AutoHeightImage.styles.tsx

import styled from "styled-components";

export const AutoHeightImageWrapper = styled.div`
  width: 100%;
  & > span {
    position: unset !important;
    & .autoImage {
      object-fit: contain !important;
      position: relative !important;
      height: auto !important;
    }
  }
`;
  • 반응형으로 만들기로 기획했으므로 화면 크기에 따라 column의 갯수를 조절하기 위해 custom hook을 공부했다.
    • style hook 관련해서 링크 추가 예정
  • ㅁㄴㅇㄹ
profile
ChatGPT-Driven Development를 지양합니다.

0개의 댓글