무엇을 학습할 것인가?
구현 요구사항
import { useState } from "react";
import PropTypes from 'prop-types'
const Counter = ({onIncrease, onDecrease}) => {
const [count, setCount] = useState(0)
const handleIncrease = () => {
setCount(count + 1)
if(onIncrease){
onIncrease()
}
}
const handleDecrease = () => {
setCount(count - 1)
if(onDecrease){
onDecrease()
}
}
return (
<div>
<p>현재 카운터 값은 {count}입니다.</p>
<button onClick={handleIncrease}>+1</button>
<button onClick={handleDecrease}>-1</button>
</div>
);
}
Counter.propTypes = {
onChange: PropTypes.func
}
export default Counter;
import React, {useState} from 'react';
import Counter from './Counter';
function App() {
const [totalCount, setTotalCount] = useState(0)
return (
<div>
Total Count : {totalCount}
<Counter
onIncrease={()=>setTotalCount(totalCount+1)}
onDecrease={()=>setTotalCount(totalCount-1)}
></Counter>
<Counter
onIncrease={()=>setTotalCount(totalCount+1)}
onDecrease={()=>setTotalCount(totalCount-1)}
></Counter>
<Counter
onIncrease={()=>setTotalCount(totalCount+1)}
onDecrease={()=>setTotalCount(totalCount-1)}
></Counter>
</div>
);
}
export default App;
pagination
콘텐츠를 여러 개 페이지에 나눠서 보여주는 UI이다.
구현 요구사항
import React from "react";
import PropTypes from 'prop-types'
const Board = ({articles}) => {
return (
<div>
{articles.map(article =>
<li key={article.id}>{article.id} | {article.title}</li>)}
</div>
)
}
Board.propTypes = {
articles: PropTypes.array
}
export default Board
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
import React, {useState} from 'react';
import Board from './Board';
import Pagination from './Pagination';
/* Pagination 컴포넌트와 Board 컴포넌트가 어떤식을 통신하는지?
App 컴포넌트를 통해 데이터를 주고 받는다! */
// Pagination 로직
function App() {
const [page, setPage] = useState(0)
const articles = new Array(100).fill().map((_,i) => ({
id: i,
title: `${i}번째 게시물`
}))
const limit = 10
const offset = page + limit
return (
<div>
<Pagination defaultPage={0} limit={10} total={articles.length}
onChange={setPage}/>
<Board articles={articles.slice(offset,offset+limit)}/>
</div>
);
}
export default App;