Files
operationSystem-front/src/components/common/Pagination/Pagination.js
2025-02-12 18:29:27 +09:00

107 lines
2.3 KiB
JavaScript

import { Link } from 'react-router-dom';
import styled from 'styled-components';
import { useEffect, useState } from 'react';
import PaginationIcon from '../../../assets/img/icon/icon-pagination.png';
const Pagination = ({ postsPerPage, totalPosts, setCurrentPage, currentPage, pageLimit }) => {
const pageNumbers = [];
const maxPage = Math.ceil(totalPosts / postsPerPage);
const [blockNum, setBlockNum] = useState(0);
for (let i = 1; i <= maxPage; i++) {
pageNumbers.push(i);
}
const v = blockNum * pageLimit;
let pArr = pageNumbers.slice(v, pageLimit + v);
useEffect(() => {
setBlockNum(0);
}, [postsPerPage, totalPosts]);
const firstPage = () => {
setBlockNum(0);
setCurrentPage(1);
};
const lastPage = () => {
setBlockNum(Math.ceil(maxPage / pageLimit) - 1);
setCurrentPage(maxPage);
};
const prePage = () => {
if (currentPage <= 1) return;
else if (currentPage - 1 <= pageLimit * blockNum) {
setBlockNum(n => n - 1);
}
setCurrentPage(n => n - 1);
};
const nextPage = () => {
if (currentPage >= maxPage) return;
else if (pageLimit * (blockNum + 1) <= currentPage) {
setBlockNum(n => n + 1);
}
setCurrentPage(n => n + 1);
};
const clickPage = number => {
setCurrentPage(number);
};
return (
<>
<PaginationWrapper>
<Button $position="0" onClick={firstPage} />
<Button $position="-20px" onClick={prePage} />
{pArr.map(number => (
<PageNum
$state={currentPage === number ? 'on' : ''}
key={number}
onClick={() => {
clickPage(number);
}}>
{number}
</PageNum>
))}
<Button $position="-40px" onClick={nextPage} />
<Button $position="-60px" onClick={lastPage} />
</PaginationWrapper>
</>
);
};
export default Pagination;
const PaginationWrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
`;
const Button = styled.button`
background: url('${PaginationIcon}') no-repeat;
background-position: ${props => props.$position} 0;
width: 20px;
height: 20px;
&:hover {
background-position: ${props => props.$position} -20px;
}
`;
const PageNum = styled(Link)`
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
color: ${props => (props.$state === 'on' ? '#2c2c2c' : '#CECECE')};
&:hover {
color: #2c2c2c;
}
`;