Skip to main content

[React] 리액트에서 페이지네이션(Pagination) 구현하기


리액트에서 페이지네이션(Pagination)을 구현하는 방법이다.



1. 동작 순서

  1. Math.ceil(data.length / postPerPage) -> 총 페이지 개수 계산
  2. 총 페이지 개수 만큼 버튼 생성
  3. 버튼 클릭 -> data에서 해당 범위 추출 -> posts에 저장
  4. posts 렌더링

2. 코드

import { useState } from 'react';

// 전체 데이터
const data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

export default function App() {
const [postPerPage, setPostPerPage] = useState(4); // 페이지당 개수
const [posts, setPosts] = useState(data.slice(0, postPerPage)); // 렌더링 되는 배열

// 렌더링 될 첫번째와 마지막 인덱스를 계산 -> 자른 배열을 posts에 저장
const handleChange = (page) => {
const firstIndex = page * postPerPage;
const lastIndex = page * postPerPage + postPerPage;

setPosts(data.slice(firstIndex, lastIndex));
};

return (
<>
{/* posts 렌더링 */}
{posts.map((post) => (
<div>{post}</div>
))}

{/* 버튼 렌더링 */}
{[...Array(Math.ceil(data.length / postPerPage)).keys()].map((page) => (
<button onClick={() => handleChange(page)}>{page}</button>
))}
</>
);
}
  • [...Array(10).keys()] : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]와 같은 표현

3. 실행

Live Editor
// 전체 데이터
const data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

function App() {
  const [postPerPage, setPostPerPage] = useState(4); // 페이지당 개수
  const [posts, setPosts] = useState(data.slice(0, postPerPage)); // 렌더링 되는 배열

  // 렌더링 될 첫번째와 마지막 인덱스를 계산 -> 자른 배열을 posts에 저장
  const handleChange = (page) => {
    const firstIndex = page * postPerPage;
    const lastIndex = page * postPerPage + postPerPage;

    setPosts(data.slice(firstIndex, lastIndex));
  };

  // live code에서는 [...Array(10).keys()] 기능이 작동 안해서 아래 함수 추가
  const makeArray = (number) => {
    const array = [];
    for (let i = 0; i < number; i++) {
      array.push(i);
    }
    return array;
  };

  return (
    <>
      {/* posts 렌더링 */}
      {posts.map((post) => (
        <div>{post}</div>
      ))}

      {/* 버튼 렌더링 */}
      {makeArray(Math.ceil(data.length / postPerPage)).map((page) => (
        <button onClick={() => handleChange(page)}>{page}</button>
      ))}
    </>
  );
}

render(<App />);
Result
Loading...