728x90
React는 SPA(Single Page Application)을 만드는데 최적화되어있다.
별도록 라우팅기능은 제공하지 않지만 react-router라는 라이브러리를 이용하여 라우팅 할 수 있다.
처음에는 직접 구현하려고 했다가 css가 이상해지고 데이터가 이상하게 보였다.
그래서 그냥 라이브러리를 이용하여 구현하기로 했다.
페이지네이션 라이브러리에도 여러개가 있는데 react-js-pagination를 사용했다.
npm install react-js-pagination
이제 페이지네이션을 구현해보자!
파일 구조!!
원래 LostFound와 Notice에 BoardList.js가 각자 있었지만
둘다 거의 (99%) 동일한 코드이기 때문에 BoardPage.js를 만들어서 index.js에서 불러주었다.
import { useState, useEffect } from 'react';
import axios from 'axios';
import styled from 'styled-components';
import Pagination from 'react-js-pagination'
const PaginationBox = styled.div`
.pagination { display: flex; justify-content: center; margin-top: 15px;}
ul { list-style: none; padding: 0; }
ul.pagination li {
display: inline-block;
width: 30px;
height: 30px;
border: 1px solid #e2e2e2;
display: flex;
justify-content: center;
align-items: center;
font-size: 1rem;
}
ul.pagination li:first-child{ border-radius: 5px 0 0 5px; }
ul.pagination li:last-child{ border-radius: 0 5px 5px 0; }
ul.pagination li a { text-decoration: none; color: #337ab7; font-size: 1rem; }
ul.pagination li.active a { color: white; }
ul.pagination li.active { background-color: #337ab7; }
ul.pagination li a:hover,
ul.pagination li a.active { color: blue; }
`
const BoardPage = ({postIdx}) => {
const [tableData, setTableData] = useState([]);
const [page, setPage] = useState(1);
const [items, setItems] = useState(5);
useEffect(() => {
// async는 이 부분이 비동기 처리를 하는 곳이라는 것을 알림
(async () => {
try {
// axios.get이 반환하는 것은 Promise 객체
// await을 붙이면 프로미스가 반환될 때까지 기다린다.
const res = await axios.get(`/board/${postIdx}`);
setTableData(res.data.products);
console.log(res.data.products);
} catch (e) {
console.error(e.message)
}
})();
}, [])
const handlePageChange = (page) => { setPage(page); };
return (
<>
{/* <List items={list}/> */}
<div className='table_list'>
<table className="table">
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">제목</th>
<th scope="col">글쓴이</th>
<th scope="col">작성일자</th>
</tr>
</thead>
<tbody className="table-group-divider">
{
tableData.slice(
items * (page - 1),
items * (page - 1) + items
).map((data) => {
return (
<tr key={data.id}>
<th scope="row">{data.id}</th>
<td>{data.title}</td>
<td>{data.nickname}</td>
<td>{data.created_at.substr(0, 10)}</td>
</tr>
);
})
}
</tbody>
</table>
</div>
<PaginationBox>
<Pagination
activePage={page}
itemsCountPerPage={items}
totalItemsCount={tableData.length - 1}
pageRangeDisplayed={5}
onChange={handlePageChange}>
</Pagination>
</PaginationBox>
</>
);
};
export default BoardPage;
index.js에서는 이렇게 BoardPage를 부르는데 때에 맞는 postIdx를 넣어서 호출한다.
밑 사진의 코드는 LostFound의 index.js이므로 postIdx를 1로 준다.
실행한 동영상 :
<조금 변경한 UI >
- 버튼의 모양과 색상, 위치
- 각 게시물의 사이즈 변경 & 일정한 사이즈가 되도록 FIX
- No 열 제거
참고 블로그 :
반응형
'프로젝트 > 정통마켓_React' 카테고리의 다른 글
[React]DB 데이터를 화면에 불러오기 (1) | 2022.08.09 |
---|---|
[React]react와 mysql 연결 (0) | 2022.08.01 |
[React] 데이터를 위한 server 만들기 [express, axios] (0) | 2022.07.28 |
[React]부트스트랩 이용하는 방법_(+결과물) (0) | 2022.07.24 |