코딩 공부 일지/React JS
react-paginate 로 페이지네이션 구현하기
헬로코딩
2022. 6. 7. 09:35
728x90

회사에서 페이지네이션 기능을 구현할 일이 생겼다. 직접 기능을 만들면 좋겠지만, 생각보다 너무 어려웠다. 그래서 찾아보니 리액트 라이브러리 중 react-paginate를 이용해서 페이지네이션을 구현할 수 있다는 것을 찾았다.
https://www.npmjs.com/package/react-paginate
react-paginate
A ReactJS component that creates a pagination.. Latest version: 8.1.3, last published: 2 months ago. Start using react-paginate in your project by running `npm i react-paginate`. There are 422 other projects in the npm registry using react-paginate.
www.npmjs.com
npm install react-paginate --save
사용법은 매우 간단하다. 예제 코드에 내가 원하는 자료를 붙여주기만 하면 된다. 라우팅으로 페이지가 이동하는 것이 아니라 자바스크립트로 가변적으로 자료를 바꿔준다.
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import ReactPaginate from 'react-paginate';
// 내가 보여줄 아이템의 리스트 - 배열 자료형으로 만들어야 한다.
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
// 아이템을 map을 이용해서 뿌려주는 구간 - 내가 보여줄 모양으로 마크업한다.
function Items({ currentItems }) {
return (
<>
{currentItems &&
currentItems.map((item) => (
<div>
<h3>Item #{item}</h3>
</div>
))}
</>
);
};
// 하단 페이지네이션 네비게이션과 페이지 리스트를 보여주는 컴포넌트
// props를 통해 한 페이지에 보여줄 아이템의 개수를 받아 재사용 가능한 컴포넌트로 사용할 수 있다.
function PaginatedItems({ itemsPerPage }) {
// We start with an empty list of items.
const [currentItems, setCurrentItems] = useState(null);
const [pageCount, setPageCount] = useState(0);
// Here we use item offsets; we could also use page offsets
// following the API or data you're working with.
const [itemOffset, setItemOffset] = useState(0);
useEffect(() => {
// Fetch items from another resources.
const endOffset = itemOffset + itemsPerPage;
console.log(`Loading items from ${itemOffset} to ${endOffset}`);
setCurrentItems(items.slice(itemOffset, endOffset));
setPageCount(Math.ceil(items.length / itemsPerPage));
}, [itemOffset, itemsPerPage]);
// Invoke when user click to request another page.
const handlePageClick = (event) => {
const newOffset = (event.selected * itemsPerPage) % items.length;
console.log(
`User requested page number ${event.selected}, which is offset ${newOffset}`
);
setItemOffset(newOffset);
};
return (
<>
<Items currentItems={currentItems} />
<ReactPaginate
breakLabel="..."
nextLabel="next >"
onPageChange={handlePageClick}
pageRangeDisplayed={5}
pageCount={pageCount}
previousLabel="< previous"
renderOnZeroPageCount={null}
/>
</>
);
}
// Add a <div id="container"> to your HTML to see the componend rendered.
ReactDOM.render(
<PaginatedItems itemsPerPage={4} />,
document.getElementById('container')
);
페이지네이션 커스터마이징을 위한 다양한 Props들의 설명도 Document에 설명이 되어 있다. 커스텀하기가 매우 용이해서 사용하기 매우 좋은 것 같다.
728x90