[React]무한 스크롤을 해보자!

LEE JOONG JAE·2022년 8월 11일

무한 스크롤이란?

데이타를 한번에 다 불러오지 않고, 일정량만 불러온 뒤 스크롤 하여 내릴 시 추가로 데이터를 더 가져 오는 기능

▶ 데이타를 한번에 불러오려면 첫 페이지에 로드가 많이 걸린다. 무한 스크롤을 이용해서 속도를 최적화 해보자.

1. 설치하기

npm install --save react-infinite-scroll-component

▶ 상기 명령어를 입력하여 설치한다.

2. 가져오기

import InfiniteScroll from 'react-infinite-scroll-component';

App.js파일에 상기 기능을 import 한다.

3. 템플릿 가져오기

  <InfiniteScroll
  dataLength={items.length} //This is important field to render the next data
  next={fetchData}
  hasMore={noMore}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
  >
  {items.map((elem,index)=>{
    return(
      <div key={index}className='container'>
        <h4>id:{elem.id}</h4>
        <p>title:{elem.title}</p>
      </div>
      
    )
  })}
  </InfiniteScroll>

▶ 상기의 InfiniteScroll Component를 삽입하면 된다.
▶ items.map으로 표현된 부분에 초기의 데이타를 넣어주고, fetchData()라는 함수를 정해서 추가로 가져올 함수를 정한다.(동적으로 코딩 필요)
▶ 끝까지 다 가져왔을 경우 endMessage를 띄워주며 noMore이란 변수를 지정해서 끝을 정해주면 됨.

profile
안녕중재

0개의 댓글