728x90
    
    
  반응형
    
    
    
  캘린더를 다루는 모듈 중 react-day-picker라는 모듈이 있다.
해당 날짜를 클릭했을 때의 이벤트를 주고 싶다면 한 번 도전해보자.
먼저 react 앱과 react-day-picker를 설치한다.
$ npx create-react-app teepo
$ npm install react-day-picker --save
$ npm i react-day-picker
그 다음 App.js 를 다음과 같이 수정하고 실행해본다.
App.js
import './App.css';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
function App() {
  return (
    <div className="App">
      <DayPicker />
    </div>
  );
}
export default App;

이렇게 달력이 잘 뜨는 것을 확인할 수 있다.
그럼 이번에는 onDayClick()을 통해 날짜를 선택할 때 하단에 해당 날짜가 출력되게끔 수정해보자.
App.js
import './App.css';
import { useState } from 'react'
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
function App() {
  const [day,setDay] = useState();
  const handleDayClick = (day) => {
    setDay(day);
  }
  return (
    <div className="App">
      <DayPicker onDayClick={handleDayClick} />
      {day ? <p>{day.toString()}</p> : <p>날짜를 선택해주세요</p>}
    </div>
  );
}
export default App;

여기서 DayPicker에 selectedDays() 메소드를 추가하면 선택한 날짜에 표시를 할 수 있다.
App.js
import './App.css';
import { useState } from 'react'
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
function App() {
  const [day,setDay] = useState();
  const handleDayClick = (day) => {
    setDay(day);
  }
  return (
    <div className="App">
      <DayPicker
        onDayClick={handleDayClick}
        selectedDays={day}/>
      {day ? <p>{day.toString()}</p> : <p>날짜를 선택해주세요</p>}
    </div>
  );
}
export default App;

HandleDayClick의 두번째 파라미터에 selected를 사용하면 이미 선택된 날짜를 취소할 수도 있다.
App.js
import './App.css';
import { useState } from 'react'
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
function App() {
  const [day, setDay] = useState();
  const [selectDay, setSelectDay] = useState(false);
  const handleDayClick = (day, { selected }) => {
    if (selected) {
      setDay(undefined);
    }
    else {
      setDay(day)
    }
  }
  return (
    <div className="App">
      <DayPicker
        onDayClick={handleDayClick}
        selectedDays={day} />
      {day ? <p>{day.toString()}</p> : <p>날짜를 선택해주세요</p>}
      
    </div>
  );
}
export default App;

728x90
    
    
  반응형
    
    
    
  'Front-End > React.js' 카테고리의 다른 글
| React.js | xlsx 모듈을 이용한 엑셀 파일 저장 (0) | 2022.02.07 | 
|---|---|
| React.js | regeneratorRuntime is not defined 에러 (0) | 2021.11.25 | 
| React.js | Intersection Observer(무한 스크롤) (4) | 2021.11.14 | 
| React.js | CSS, SASS, SCSS (0) | 2021.11.02 | 
| React.js | API 연동 | 마지막 (0) | 2021.10.08 |