import { useState } from "react";
import styled from "styled-components";
const Pagination = ({ slicePages, currentArray, currentPage, onPageChange }) => {
const [isActive, setIsActive] = useState([true, false, false, false, false]);
const setPage = (newCurrentArray) => {
onPageChange(newCurrentArray, slicePages[newCurrentArray][0]);
};
const isactive = (page) => {
// to focus on the current page
const initialActive = [true, false, false, false, false];
initialActive[0] = false
initialActive[(page - 1) % 5] = true
setIsActive(initialActive);
}
const pagination = (slicePages, currentPage) => {
// to show such as [1, 2, 3, 4, 5] button
return slicePages[currentArray]?.map((page, index) => (
<PageButton
key={index}
onClick={() => {onPageChange(currentArray, page); isactive(page)}}
className={isActive[(page - 1) % 5] ? 'active' : ''}
>
{page}
</PageButton>
));
}
return (
<Paging>
<SideBtn
onClick={()=>{setPage(currentArray - 1, slicePages); isactive(1)}}
disabled={currentArray === 0}
>
<
</SideBtn>
{pagination(slicePages, currentPage)}
<SideBtn
onClick={()=>{setPage(currentArray + 1, slicePages); isactive(1)}}
disabled={currentArray === slicePages.length - 1}>
>
</SideBtn>
</Paging>
)
}
const PageButton = styled.button`
font-size: 27px;
color: #4659A9;
border: transparent;
background-color: transparent;
margin-bottom: 40px;
&.active {
color: #ffffff;
background-color: #4659A9;
}
`
const SideBtn = styled.button`
font-size: 27px;
color: #4659A9;
border: transparent;
background-color: transparent;
`
const Paging = styled.div`
grid-area: pagination;
margin-top: 30px;
`;
export default Pagination;
원래 코드는 이랬다. 하지만 문제가 생겼다.
책 검색 필터에 따라 currentpage가 1로 가야한다. state는 바뀌는데 정작 페이지에 대한 포커스가 바뀌지 않았다. 왜냐. pagination 함수에서 currentpage를 쓰지 않기 때문에. 그래서 쓰는 쪽으로 바꿨다.
const Pagination = ({ slicePages, currentArray, currentPage, onPageChange }) => {
const setPage = (newCurrentArray) => {
onPageChange(newCurrentArray, slicePages[newCurrentArray][0]);
};
const isactive = (page) => {
// to focus on the current page
// const initialActive = [false, false, false, false, false];
// initialActive[0] = false
return currentPage === page;
}
const pagination = (slicePages, currentPage) => {
// to show such as [1, 2, 3, 4, 5] button
return slicePages[currentArray]?.map((page, index) => (
<PageButton
key={index}
onClick={() => {onPageChange(currentArray, page); }}
className={isactive(page) ? 'active' : ''}
>
{page}
</PageButton>
));
}
더 간결해졌다.
'웹 > React' 카테고리의 다른 글
[React] getquerydata undefined 문제 (0) | 2024.01.13 |
---|---|
[React] onClick에 2개의 함수를 넣고 싶다면 (0) | 2023.09.27 |
[React] 검색텍스트 입력 후 버튼 누르면 검색되게 하기, react에서 입력값 가져오기 (0) | 2023.09.21 |
[React] useState를 이용해 리스트에 값 추가하기 (0) | 2023.09.18 |
[React] 흐르는 텍스트 시작 지점 설정 (0) | 2023.09.17 |
댓글