반응형
데이터가 정상적으로 렌더링되는 것을 확인했으니 이제 상단 헤더의 실제 작동을 시켜본다.
상단 헤더의 월 이동을 도와줄 함수와 중간 텍스트 자리에 들어갈 텍스트를 생성한다.
const [curDate, setCurDate] = useState(new Date());
const headText = `${curDate.getFullYear()}년 ${curDate.getMonth() + 1}월`;
const decreaseMonthHandler = () => {
setCurDate(
new Date(curDate.getFullYear(), curDate.getMonth() - 1, curDate.getDate())
);
};
const increaseMonthHandler = () => {
setCurDate(
new Date(curDate.getFullYear(), curDate.getMonth() + 1, curDate.getDate())
);
};
const Home = () => {
...
return (
<>
<Header
headText={headText}
leftBtn={<Button text="◀" onClick={decreaseMonthHandler} />}
rightBtn={<Button text="▶" onClick={increaseMonthHandler} />}
/>
...
</>
);
};
export default Home;
Json형태의 데이터를 사용할 것이 아니므로 컨텍스트를 살짝 수정했다.
//컨텍스트 생성
export const DiaryContext = createContext({
diary: [],
onCreate: () => {},
onEdit: () => {},
onRemove: () => {},
});
const Home = () => {
const diaryCtx = useContext(DiaryContext);
...
return (
<>
<Header
headText={headText}
leftBtn={<Button text="◀" onClick={decreaseMonthHandler} />}
rightBtn={<Button text="▶" onClick={increaseMonthHandler} />}
/>
<h1>Home</h1>
{diaryCtx.diary.map((it) => (
<div key={it.id}>{it.content}</div>
))}
</>
);
};
export default Home;
배열로 넘어온 데이터가 잘 출력되었다.
시간에 따른 데이터 출력
월마다 데이터를 출력하고 싶다.
const Home = () => {
...
const [data, setData] = useState([]);
useEffect(() => {
if (diaryCtx.diary) {
//현재 년월의 첫번째 날
const firstDay = new Date(
curDate.getFullYear(),
curDate.getMonth(),
1
).getTime();
//다음 달 0일까지
const lastDay = new Date(
curDate.getFullYear(),
curDate.getMonth() + 1,
0
).getTime();
//이번 달 일기를 추리기
setData(
diaryCtx.diary.filter((it) => firstDay <= it.date && it.date <= lastDay)
);
}
}, [diaryCtx.diary, curDate]); //일기가 변화하거나 현재 시간이 변화할때 리렌더링됨
...
data state를 새로 만들고, 이번 달의 일기를 추려 data에 저장한다.
useEffect를 이용해 일기리스트가 변화하거나 현재 시간이 변화하면 리렌더링되도록 했다.
일기가 저장된 달의 일기만 화면에 표시하고 있다.
반응형
'웹 프로그래밍 > 🌜꿈 일기장' 카테고리의 다른 글
[React] 꿈 일기 기록 사이트 제작 일지-11. 일기 검색 기능 추가 (0) | 2023.09.27 |
---|---|
[React] 꿈 일기 기록 사이트 제작 일지-10. 사용자가 장르를 수정할 수 있는 `사용자 장르 추가/삭제 기능` 구현 (+ localStorage) (2) | 2023.09.27 |
[React] 꿈 일기 기록 사이트 제작 일지-6. 일기아이템 생성 및 조회 페이지 이동 구현과 CSS 스타일링 (0) | 2023.09.25 |
[React] 꿈 일기 기록 사이트 제작 일지-5. 일기 정렬 기능 및 페이지 이동 버튼 구현 (0) | 2023.09.25 |
[React] 꿈 일기 기록 사이트 제작 일지-2. 리액트 프로젝트 시작 및 페이지 만들기, 라우터 설정, 공용 컴포넌트 설정 (0) | 2023.09.22 |
[React] 꿈 일기 기록 사이트 제작 일지-1. 기획 및 디자인 구상, url 설계 (0) | 2023.09.22 |