매달마다 데이터를 받아서 해당 데이터를 달력에 표시하는게 필요했다.
서버에 연도와 달을 보내면 해당 연도와 달에 해당하는 데이터가 들어온다. 데이터의 날짜는 2023-03-15 형태로 들어와야한다. 전체적인 코드는 이렇다.
import { Calendar } from 'react-native-calendars';
...
useEffect(() => {
getCalendar(year, month, setList, setCenter, setLoading);
}, [month]);
const markedDates = list.reduce((acc, current) => {
const formattedDate = current.date
acc[formattedDate] = { marked: true };
return acc;
}, {});
const [selectedDate, setSelectedDate] = useState(
dayjs().format("YYYY-MM-DD")
);
const markedSelectedDates = {
...markedDates,
[selectedDate]: {
selected: true,
marked: markedDates[selectedDate]?.marked,
}
}
const a = []
const daySchedule = (day) => {
list.forEach((v) => {
if (v.lectureDate === day) {
a.push(v)
}
})
}
...
return(
<Calendar
onDayPress={day => {
// console.log('selected day', day)
setSelectedDate(day.dateString),
daySchedule(day.dateString)
}}
markedDates={markedSelectedDates}
monthFormat={'MMM, yyyy'}
hideExtraDays={true}
onPressArrowLeft={subtractMonth => subtractMonth()}
onPressArrowRight={addMonth => addMonth()}
disableAllTouchEventsForDisabledDays={true}
onMonthChange={month => {
// console.log('month changed', month);
setMonth(month.month)
setYear(month.year)
}}
/>
)
천천히 뜯어보면
Calendar 에서 onMonthChange로 달이 바뀔 때 마다 getCalendar(서버에서 해당연도 해당 달의 데이터 받아오는 함수) 함수가 실행되면서 list가 들어오게 된다. 그럼 그 다음으로 markedDates가 실행되고 그 결과값으로
{
"2023-02-14": {"marked": true},
"2023-03-01": {"marked": true},
"2023-03-09": {"marked": true},
"2023-03-16": {"marked": true}
}
이런 모양의 데이터값이 도출된다 . 그럼 이데이터를 사용해서 캘린더에 넣으면 사진처럼 마킹된 날짜가 나오게 된다. markedSelectedDates얘는 선택한 날짜를 보여주기 위해서 selected 항목도 추가시켜 주는 부분이다. markedSelectedDates를 통과하고 나면 결과값이
--> 3/14일 클릭시
{"2023-02-14": {"marked": true},
"2023-03-01": {"marked": true},
"2023-03-09": {"marked": true},
"2023-03-14": {"marked": undefined, "selected": true},
"2023-03-16": {"marked": true}}
이렇게 보여지게 되고 내장 css를 추가하면 원하는 모양이 된다.
추가적으로 특정 날짜 클릭시 해당 날짜에 포함되는 데이터 값을 받아오기 위해서 daySchedule함수를 사용하면 된다!
다시봐도 배열함수의 세계는 재밌다 후욱