본문 바로가기
웹 프로그래밍/🌜꿈 일기장

[React] 꿈 일기 기록 사이트 제작 일지-4. Home.js 작성한 월에 맞는 일기 리스트 렌더링

by 청량리 물냉면 2023. 9. 24.
반응형

데이터가 정상적으로 렌더링되는 것을 확인했으니 이제 상단 헤더의 실제 작동을 시켜본다. 

상단 헤더의 월 이동을 도와줄 함수와 중간 텍스트 자리에 들어갈 텍스트를 생성한다.

  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를 이용해 일기리스트가 변화하거나 현재 시간이 변화하면 리렌더링되도록 했다.

일기가 저장된 달의 일기만 화면에 표시하고 있다. 

 

반응형