๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

์‚ฌ์šฉ์‚ฌ๋ก€ - ํŽ˜์ด์ง€๋„ค์ด์…˜ ๋งŒ๋“ค๊ธฐ ๋ณธ๋ฌธ

๐Ÿ“š Language & CS knowledge/React

์‚ฌ์šฉ์‚ฌ๋ก€ - ํŽ˜์ด์ง€๋„ค์ด์…˜ ๋งŒ๋“ค๊ธฐ

Daehyunii 2022. 12. 18. 23:58

App.js

import { useState } from "react";
import Board from "./components/Board";
import Pagination from "./components/Pagination";

function App() {
  const [page, setPage] = useState(0);

  const articles = new Array(100).fill().map((_, i) => {
    return {
      id: i,
      title: `${i}๋ฒˆ ๊ฒŒ์‹œ๋ฌผ`,
    };
  });

  const limit = 6;
  const offset = page * limit;

  return (
    <div>
      <Pagination
        defaultPage={0}
        limit={limit}
        total={articles.length}
        onChange={setPage}
      />
      <Board articles={articles.slice(offset, offset + limit)} />
    </div>
  );
}

export default App;

Pagination.js

import { useState } from "react";

const Pagination = ({ defaultPage, limit, total, onChange }) => {
  const [page, setPage] = useState(defaultPage);
  const totalPage = Math.ceil(total / limit);

  const handleChangePage = (newPage) => {
    onChange(newPage);
    setPage(newPage);
  };
  return (
    <div>
      <button
        onClick={() => {
          page !== 0 && handleChangePage(page - 1);
        }}
      >
        ์ด์ „
      </button>
      {Array.from(new Array(totalPage), (_, i) => i)
        .filter((i) => {
          if (page < 3) {
            return i < 5;
          } else if (page > totalPage - 3) {
            return i >= totalPage - 5;
          }
          return i >= page - 2 && i <= page + 2;
        })
        .map((i) => (
          <button
            key={i}
            onClick={() => handleChangePage(i)}
            style={{ backgroundColor: page === i ? "red" : undefined }}
          >
            {i + 1}
          </button>
        ))}
      <button
        onClick={() => {
          page + 1 !== totalPage && handleChangePage(page + 1);
        }}
      >
        ๋‹ค์Œ
      </button>
    </div>
  );
};

export default Pagination;

Board.js

import PropTypes from "prop-types";

const Board = ({ articles }) => {
  return (
    <ul>
      {articles.map((article) => (
        <li key={article.id}>
          {article.id} | {article.title}
        </li>
      ))}
    </ul>
  );
};

Board.propTypes = {
  articles: PropTypes.array,
};

export default Board;