화면에 달력을 표시하고, 이를 수정하는 예제 학습하기
사전 설치 라이브러리
yarn add react-native-calendars
yarn add react-native-modal-datetime-picker @react-native-community/datetimepicker
설치 이후 시뮬레이터 재기동 필수
달력에 표시하기
달력에 특정 일자를 선택한 표시(selected), 체크한 표시(marked) 남기는 예제
import React from 'react';
import {Calendar} from 'react-native-calendars';
import {StyleSheet} from 'react-native';
function CalendarView() {
const markedDates = {
'2023-08-05': {
selected: true,
},
'2023-08-04': {
marked: true,
},
'2023-08-03': {
marked: true,
},
};
return (
<Calendar
style={styles.calendar}
markedDates={markedDates}
theme={{
selectedDayBackgroundColor: '#009688',
arrowColor: '#009688',
dotColor: '#009688',
todayTextColor: '#009688',
}}
/>
);
}
const styles = StyleSheet.create({
calendar: {
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
}));
export default CalendarView;
- markedDates : 일자와 속성을 객체로 정의하여 입력하는 Props, 해당 일자로 달력에 표시됨
- theme : style과 같이 색상과 같은 스타일 설정을 하는 Props
* 추가 Props
- onDayPress : 달력을 선택했을 때 호출되는 함수 등록
사용 예제)
<Calendar
style={styles.calendar}
markedDates={markedSelectedDate}
onDayPress={(day) => {
onSelectDate(day.dateString);
}}
(...)
[day 객체 구성]
- dateString : "2023-08-05"
- day : 5
- month : 8
- timestamp : 1629676800000
- year : 2023
함께 활용하면 좋은 Hook : useMemo
동일한 계산을 반복해야 할 때 불필요한 연산을 제거하기 위해 이전에 계산한 값을 재사용해 처리하는 Hook
사용 예제)
const value = useMemo(() => compute(a, b), [a, b]);
위와 같이 사용하면 a, b 값이 바뀔때에만 compute(a, b) 함수가 호출됨
* useMemo를 활용하여 markedDates 객체를 계산하는 함수를 호출하면 됨
DateTimePickerModal 컴포넌트 사용하기
기본 사용 예제)
<DateTimePickerModal
onConfirm={onConfirm}
onCancel={onCancel}
mode={mode}
date={date}
isVisible={visible}
/>
- onConfirm : 날짜를 선택을 완료했을 때 호출되는 함수. 선택한 날짜의 Date 객체가 파라미터로 호출됨.
- onCancel : 날짜 선택을 취소했을 때 호출되는 함수.
- mode : 모달창의 모드. date, time, datetime 세가지 존재함.
- date : 초기값으로 설정할 Date 객체 타입의 값
- isVisible : 모달창 표시 여부 체크
기본적인 활용 개념은 컴포넌트를 생성해놓고, isVisible 값을 통해 보였다 안보였다 상태 변경을 시켜서 활용함
'React Native' 카테고리의 다른 글
React Native) Firestore 활용하기 (0) | 2023.08.17 |
---|---|
React Native) Firebase 적용하기 (0) | 2023.08.06 |
React Native) Animated로 애니메이션 적용하기 (0) | 2023.08.02 |
React Native) Pressable, useRef, uuid, date-fns 활용하기 (0) | 2023.08.02 |
React Native) Context API 사용하기 (0) | 2023.08.02 |