오늘은 진행하던 프로젝트에서 타입 스크립트를 사용하여 캘린더 퍼블리싱을 진행하였습니다.

import React, { useState } from 'react';
import styled from 'styled-components';
import CalendarButton from './CalendarButton'; // CalendarButton 컴포넌트 import

const CalendarContainer = styled.div`
    margin-top: 40px;
`;

const CalendarNavigation = styled.div`
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
`;

const NavButton = styled.button`
    background-color: transparent;
    border: none;
    color: #000000;
    font-size: 26px;
    cursor: pointer;

    &:hover {
        color: #007bff;
    }
`;

const MonthYearTitle = styled.span`
    font-size: 26px;
    font-weight: bold;
`;

const WeekdaysRow = styled.div`
    display: flex;
    justify-content: space-around;
    text-align: center;
    font-weight: medium;
    color: #2f2f2f;
    margin-top: 25px;
    margin-bottom: 10px;
`;

interface WeekdayCellProps {
    isSunday?: boolean;
    isSaturday?: boolean;
}

const WeekdayCell = styled.div<WeekdayCellProps>`
    width: 14.28%;
    color: ${(props: WeekdayCellProps): string => {
        return props.isSunday
            ? '#ff4343'
            : props.isSaturday
              ? '#0085ff'
              : '#2f2f2f';
    }};

    abbr {
        text-decoration: none;
    }
`;

const DaysGrid = styled.div`
    display: flex;
    flex-direction: column;
`;

const WeekRow = styled.div`
    display: flex;
    width: 100%;
`;

interface DayCellProps {
    isCurrentMonth: boolean;
    hasEvent?: boolean;
}

const DayCell = styled.div<DayCellProps>`
    flex: 1;
    padding: 15px 15px;
    font-size: 18px;
    background-color: ${(props: DayCellProps): string => {
        if (props.hasEvent) {
            return '#e0f0ff'; // 일정 있는 날 색상 변경 (원래 오늘 날짜 색상)
        }
        return '#ececec'; // 다른 날짜 기본 배경색
    }};
    border-radius: 13px;
    text-align: center;
    margin: 10px 5px;
    cursor: pointer;
    color: ${(props: DayCellProps): string => {
        return props.isCurrentMonth ? '#000' : '#aaa';
    }};

    &:hover {
        background-color: ${(props: DayCellProps): string => {
            return props.hasEvent ? '#d4e5f6' : '#e0f0ff'; // hover 시 일정 있는 날짜 색상 유지
        }};
    }

    position: relative;
`;

const EventDot = styled.div`
    width: 6px;
    height: 6px;
    background-color: #40a3ff;
    border-radius: 50%;
    position: absolute;
    bottom: 5px;
    left: 50%;
    transform: translateX(-50%);
`;

const ScheduleButtonContainer = styled.div`
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
`;

const ProjectCalendar: React.FC = () => {
    const today = new Date();
    const [currentDate, setCurrentDate] = useState<Date>(new Date());
    const [isSelectingDates, setIsSelectingDates] = useState<boolean>(false);
    const [selectedStartDate, setSelectedStartDate] = useState<Date | null>(
        null,
    );
    const [selectedEndDate, setSelectedEndDate] = useState<Date | null>(null);

    // 일정이 있는 날짜 목록 (예: 이벤트 데이터)
    const eventDates = [
        new Date(2024, 9, 14), // 2024년 10월 14일에 일정
        new Date(2024, 9, 20), // 2024년 10월 20일에 일정
        // 추가 일정...
    ];

    const getMonthYear = (date: Date): string => {
        return date.toLocaleString('en-US', { month: 'long' });
    };

    const prevMonth = (): void => {
        setCurrentDate(
            new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1),
        );
    };

    const nextMonth = (): void => {
        setCurrentDate(
            new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1),
        );
    };

    const getWeekdays = (): string[] => {
        return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    };

    const generateCalendar = (): Date[][] => {
        const startOfMonth = new Date(
            currentDate.getFullYear(),
            currentDate.getMonth(),
            1,
        );
        const endOfMonth = new Date(
            currentDate.getFullYear(),
            currentDate.getMonth() + 1,
            0,
        );

        const dates: Date[][] = [];
        const current = new Date(startOfMonth);
        current.setDate(current.getDate() - current.getDay());

        while (current <= endOfMonth || current.getDay() !== 0) {
            const week: Date[] = [];

            for (let i = 0; i < 7; i += 1) {
                week.push(new Date(current));
                current.setDate(current.getDate() + 1);
            }

            dates.push(week);
        }

        return dates;
    };

    const isSameDay = (date1: Date, date2: Date): boolean => {
        return (
            date1.getFullYear() === date2.getFullYear() &&
            date1.getMonth() === date2.getMonth() &&
            date1.getDate() === date2.getDate()
        );
    };

    const handleDateClick = (date: Date): void => {
        if (isSelectingDates) {
            if (!selectedStartDate) {
                setSelectedStartDate(date);
            } else if (!selectedEndDate) {
                if (date >= selectedStartDate) {
                    setSelectedEndDate(date);
                } else {
                    setSelectedEndDate(selectedStartDate);
                    setSelectedStartDate(date);
                }
            } else {
                setSelectedStartDate(date);
                setSelectedEndDate(null);
            }
        } else {
            console.log(date);
        }
    };

    const dates: Date[][] = generateCalendar();

    return (
        <CalendarContainer>
            <CalendarNavigation>
                <NavButton type="button" onClick={prevMonth}>
                    &lt;
                </NavButton>
                <MonthYearTitle>{getMonthYear(currentDate)}</MonthYearTitle>
                <NavButton type="button" onClick={nextMonth}>
                    &gt;
                </NavButton>
            </CalendarNavigation>
            <WeekdaysRow>
                {getWeekdays().map((day: string, index: number) => {
                    return (
                        <WeekdayCell
                            key={day}
                            isSunday={index === 0}
                            isSaturday={index === 6}
                        >
                            <abbr title={day}>{day}</abbr>
                        </WeekdayCell>
                    );
                })}
            </WeekdaysRow>
            <DaysGrid>
                {dates.map((week: Date[]) => {
                    return (
                        <WeekRow key={week[0].toISOString()}>
                            {week.map((date: Date) => {
                                const isCurrentMonth =
                                    date.getMonth() === currentDate.getMonth();

                                // 일정이 있는 날짜인지 확인
                                const hasEvent = eventDates.some((eventDate) =>
                                    isSameDay(eventDate, date),
                                );

                                return (
                                    <DayCell
                                        key={date.toISOString()}
                                        isCurrentMonth={isCurrentMonth}
                                        hasEvent={hasEvent}
                                        onClick={() => {
                                            handleDateClick(date);
                                        }}
                                    >
                                        {date.getDate()}
                                        {hasEvent && <EventDot />}
                                    </DayCell>
                                );
                            })}
                        </WeekRow>
                    );
                })}
            </DaysGrid>
            <ScheduleButtonContainer>
                <CalendarButton
                    isSelectingDates={isSelectingDates}
                    hasSelectedDates={!!selectedStartDate}
                    onClick={() => {
                        if (isSelectingDates) {
                            if (selectedStartDate && selectedEndDate) {
                                console.log(
                                    '선택된 시작 날짜:',
                                    selectedStartDate,
                                );
                                console.log(
                                    '선택된 종료 날짜:',
                                    selectedEndDate,
                                );
                                setIsSelectingDates(false);
                                setSelectedStartDate(null);
                                setSelectedEndDate(null);
                            } else if (selectedStartDate) {
                                console.log('종료 날짜를 선택하세요.');
                            }
                        } else {
                            setIsSelectingDates(true);
                            setSelectedStartDate(null);
                            setSelectedEndDate(null);
                            console.log('회의 일정잡기 버튼 클릭');
                        }
                    }}
                    onCancel={() => {
                        setIsSelectingDates(false);
                        setSelectedStartDate(null);
                        setSelectedEndDate(null);
                        console.log('취소 버튼 클릭');
                    }}
                />
            </ScheduleButtonContainer>
        </CalendarContainer>
    );
};

export default ProjectCalendar;
import React from 'react';
import styled from 'styled-components';

interface CalendarButtonProps {
    isSelectingDates: boolean;
    hasSelectedDates: boolean;
    onClick: () => void;
    onCancel?: () => void;
}

const ButtonWrapper = styled.div`
    display: flex;
    gap: 10px; /* 버튼 간의 간격 */
    margin-top: -2%;
`;

const Button = styled.button<CalendarButtonProps>`
    background-color: ${(props): string => {
        return props.isSelectingDates && !props.hasSelectedDates
            ? '#CCCCCC'
            : '#40a3ff';
    }};
    color: #ffffff;
    border: none;
    padding: 8px 20px;
    font-size: 16px;
    border-radius: 10px;
    cursor: pointer;

    &:hover {
        background-color: ${(props): string => {
            return props.isSelectingDates && !props.hasSelectedDates
                ? '#CCCCCC'
                : '#3392e6';
        }};
    }
`;

const CancelButton = styled.button`
    background-color: #40a3ff;
    color: #ffffff;
    border: none;
    padding: 8px 20px;
    font-size: 16px;
    border-radius: 10px;
    cursor: pointer;

    &:hover {
        background-color: #3392e6;
    }
`;

const CalendarButton: React.FC<CalendarButtonProps> = ({
    isSelectingDates,
    hasSelectedDates,
    onClick,
    onCancel,
}) => {
    console.log('isSelectingDates:', isSelectingDates);
    console.log('onCancel:', onCancel);

    return (
        <ButtonWrapper>
            {isSelectingDates && onCancel && (
                <CancelButton type="button" onClick={onCancel}>
                    취소
                </CancelButton>
            )}
            <Button
                type="button"
                isSelectingDates={isSelectingDates}
                hasSelectedDates={hasSelectedDates}
                onClick={onClick}
            >
                회의 일정잡기
            </Button>
        </ButtonWrapper>
    );
};

// 기본값 설정
CalendarButton.defaultProps = {
    onCancel: () => {}, // 기본값으로 빈 함수 설정
};

export default CalendarButton;