1차 프로젝트 react-infinite-scroll-component 적용 방법

LB·2021년 3월 28일
0

프로젝트를 진행하면서 피드 페이지에 무한 스크롤이 있었다. 스크롤이 끝에 닿으면 다음 데이터를 불러와 피드를 보여주는 형식

무한스크롤 기능을 구현하기 위해 react-infinite-scroll-component 라이브러리를 이용해 구현하였다.

  <InfiniteScroll
    dataLength={this.state.feedList.length} // 
    next={this.nextData} // 
    hasMore={true} // 
  >
  <FeedList
    profile_picture={list.profile_picture}
    username={list.username}
    ...
  />
 </InfiniteScroll>

InfiniteScroll 옵션
dataLength -> 스크롤이 바닥에 닿을때 마다 몇개의 데이터를 뿌려줄건지에 대한 길이 설정(현재 feedList에 보여지는 데이터 길이는 4개이다)
next -> 스크롤이 바닥에 닿을때 다음 데이터를 보여주는 함수 적용
hasMore -> 이 옵션이 true 이면 다음 데이터를 보여주고 false 이면 스크롤이 바닥에 닿아도 다음데이터를 안보여준다

 componentDidMount() {
    this.nextData();
  }

  nextData = () => {
    fetch(`/data/data${this.state.page}.json`, {
      method: "GET",
    })
      .then(res => res.json())
      .then(data =>
        this.setState({
          feedList: this.state.feedList.concat(data),
          page: this.state.page + 1,
        })
      );
  };

페이지가 끝에 닿을때 마다 nextData() 에서 fetch api로 데이터를 가져와 feedList 에 추가 시키고 page 번호를 1씩 증가 하도록 코드를 짜놨다.

profile
아자

0개의 댓글