[React] - react-calendar 사용하기
다이어리 프로젝트를 진행하고 있는데, 이번에는 달력 페이지를 구현했다.
달력 페이지는 크게 두개의 기능을 구현했는데, 일정(schedule)과 to do list
후에 이 투 두 리스트의 결과 값을 가지고 차트로 만들어 한달의 목표치를 한 눈으로 확인 할 수 있는 페이지도 추가할건데, 그렇게 하기 위해선 당근 달력이 필요하다.
달력은 사람들이 가장 많이 쓰는 react-calendar를 사용했는데, 다른 사람들의 정보도 얻기 쉽고, 커스텀도 가능하고 또한 현재도 계속해서 개발을 진행한다는 점이 마음에 들었다.
react-calendar 사용법은 이러하다.
1. npm으로 라이브러리 다운
npm install react-library moment
리액트-라이브러리는 달력라이브러리고, moment는 날짜 format을 위한 라이브러리다.
직접 yyyy-mm-dd로 만들어도 되지만, 캘린더 라이브러리에 해당 기능이 함께 지원되니 설치하면 좋다.
2. 초반 코드 설정
import { Calendar } from 'react-calendar';
import 'react-calendar/dist/Calendar.css'; // library custom css
import { useState } from "react";
const CalendarPage = () => {
// todayValue와 onChange 초기화
const [todayValue, onChange] = useState<Value>(new Date());
// 클릭한 날짜를 저장하는 상태
const [selectedDate, setSelectedDate] = useState<Date | null>(null);
return (
<Calendar
onChange={onChange}
value={todayValue}
formatDay={(_, date) => moment(date).format("D")}
/>
)
}
export default CalendarPage;
const [todayValue, onChange] = useState<Value>(new Date());를 통해 해당 값들을 초기화 해주고, onChange 기능을 통해 todayValue 변수에 현재 날짜인 new Date()를 초기값으로 설정해준다.
이 때 moment를 통해 날짜를 D 형태(1, 2, ... 30, 31)로 format해준다.
3. 필요한 코드 추가
https://www.npmjs.com/package/react-calendar?activeTab=readme
react-calendar
Ultimate calendar for your React app.. Latest version: 5.1.0, last published: 14 days ago. Start using react-calendar in your project by running `npm i react-calendar`. There are 502 other projects in the npm registry using react-calendar.
www.npmjs.com
여기서 user guide 란에서 props를 확인할 수 있는데, 나에게 필요한 기능은 onClickDay로 날짜를 선택했을 때 이벤트를 인식하는데 추가로 이 해당 날짜의 값을 전달했다.
// 날짜 클릭 시 자식에게 날짜 전달
const deleverDate = (date: Date) => {
setSelectedDate(date);
}
<Calendar
onChange={onChange}
value={todayValue}
formatDay={(_, date) => moment(date).format("D")}
onClickDay={(value) => {
deleverDate(value); // 클릭한 날짜를 전달
}}
/>
4. 달력 커스텀
달력 커스텀은 import 'react-calendar/dist/Calendar.css'를 상단에 선언한 뒤 node-module -> react-calendar -> dist -> Calendar.css 파일을 연 뒤에 수정하여 커스텀을 할 수 있다.
이 때 터미널을 restart 해줘야 변경된 custom css를 확인할 수 있다.