React에서는 일반적으로 사용하는 jquery용 datepicker가 호환이 안되기 때문에
React 전용 datepicker를 사용해야 합니다.
저는 HackerOne에서 배포해준 react-datepicker 라이브러리를 사용했습니다.
react-datepicker를 적용하는 것까지는 좋았으나 제가 원하는 세팅을 설정하는데 정말 많은 시행착오를 겪었어야 했습니다.
따라서 저랑 비슷한 datepicker 환경을 원하시는 분들이 삽질을 하지 않도록 공유하고자 합니다.
우선, 제가 설정한 react-datepicker props 목록과 정의한 함수들을 나열해보겠습니다.
- locale: 달력을 한글화
- minDate: 과거 날짜는 선택할 수 없게 disable
- popperModifiers: 모바일 웹에서 화면을 벗어나지 않게 하기
- popperPlacement: datepicker를 선택했을 때 팝업이 화면 중앙에 나타나도록 설정
- css 수정: 팝업 크기 키우기
- dayClassName: 토요일 날짜는 파란색, 일요일 날짜는 빨간색으로 설정
- getDayName: 날짜를 매개변수로 전달 시 한글 요일을 반환해주는 함수
- getFormattedDate: 날짜를 매개변수로 전달 시 월/일 형태로 날짜를 반환해주는 함수
* 참고로 react-datepicker.css를 수정해야 할 경우 css 파일을 node_modules에서 직접 꺼내서 수정해주셔야 합니다.
* [추가: 6/17] css에서 saturday와 sunday class에 pointer-events: none 을 추가해주면 사용자들이 주말을 선택 못하게 할 수 있습니다!
간단한 구현 코드입니다.
App.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react' | |
import DatePicker, { registerLocale, setDefaultLocale } from "react-datepicker"; | |
import "./css/react-datepicker.css"; | |
import ko from 'date-fns/locale/ko'; | |
registerLocale('ko', ko); | |
function App() { | |
// 달력 날짜 변경 시 기준점이 되는 날짜 | |
const [startDate, setStartDate] = useState(new Date()); | |
// https://reactdatepicker.com/ 참고 | |
const ExampleCustomInput = ({ value, onClick }) => ( | |
<button class="example-custom-input" onClick={onClick}> | |
{value} | |
</button> | |
); | |
// 월/일 | |
const getFormattedDate = (date) => { | |
const month = date.toLocaleDateString('ko-KR', { | |
month: 'long', | |
}); | |
const day = date.toLocaleDateString('ko-KR', { | |
day: 'numeric', | |
}); | |
return `${month.substr(0, month.length - 1)}/${day.substr(0, day.length - 1)}`; | |
} | |
// 요일 반환 | |
const getDayName = (date) => { | |
return date.toLocaleDateString('ko-KR', { | |
weekday: 'long', | |
}).substr(0, 1); | |
} | |
// 날짜 비교시 년 월 일까지만 비교하게끔 | |
const createDate = (date) => { | |
return new Date(new Date(date.getFullYear() | |
, date.getMonth() | |
, date.getDate() | |
, 0 | |
, 0 | |
, 0)); | |
} | |
return ( | |
<> | |
<DatePicker | |
locale="ko" // 달력 한글화 | |
selected={startDate} // 날짜 state | |
onChange={setStartDate} // 날짜 설정 콜백 함수 | |
customInput={<ExampleCustomInput />} | |
minDate={new Date()} // 과거 날짜 disable | |
popperModifiers={{ // 모바일 web 환경에서 화면을 벗어나지 않도록 하는 설정 | |
preventOverflow: { | |
enabled: true, | |
}, | |
}} | |
popperPlacement="auto" // 화면 중앙에 팝업이 뜨도록 | |
// 토요일, 일요일 색깔 바꾸기 위함 | |
dayClassName={date => | |
getDayName(createDate(date)) === '토' ? "saturday" | |
: | |
getDayName(createDate(date)) === '일' ? "sunday" : undefined | |
} | |
/> | |
</> | |
); | |
} |
react-datepicker.css
css 같은 경우 해당 코드만 상단에 추가해주시면 됩니다.
important를 남발하면 안 된다는 것을 알고 있지만 어쩔 수 없었습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.react-datepicker { | |
font-size: 1.3rem !important; | |
} | |
.react-datepicker__current-month { | |
font-size: 1.5rem !important; | |
} | |
.react-datepicker__header { | |
padding-top: 6px !important; | |
} | |
.react-datepicker__navigation { | |
top: 13px !important; | |
} | |
.react-datepicker__day-name, .react-datepicker__day { | |
margin: 0.5rem !important; | |
} | |
.saturday { | |
color: rgb(0, 0, 255) !important; | |
} | |
.sunday { | |
color: rgb(255, 0, 0) !important; | |
} | |
.react-datepicker__day--disabled { | |
color: #cccccc !important; | |
} |
* dayClassName props를 응용한다면 공휴일 또한 빨간색으로 표기 가능할 것 같습니다.
[react 버전] 16.13.1
[react-datepicker 버전]: 2.14.1
[출처]
반응형
'[DEV] 기록' 카테고리의 다른 글
백준 input 파일을 읽어오는 방법 (0) | 2020.05.16 |
---|---|
react-select 커스텀 설정 (0) | 2020.05.07 |
비주얼 스튜디오에서 C4996 에러가 발생할 경우 (2) | 2020.05.06 |
React axios 사용 예시 (0) | 2020.04.23 |
React 자식 Component에서 부모 Component로 데이터 전달하는 방법 (2) | 2020.04.22 |