appointments-software / frontend / app / src / components / common / Calendar.js
Calendar.js
Raw
export const months = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];
const Calendar = (props) => {
  const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const dates = [];
  const separatedDates = [];
  const firstDay = new Date(props.year, props.month, 1).getDay();
  const lastDate = new Date(props.year, props.month + 1, 0).getDate();

  //fills with 0 up till the first weekday of the month
  for (let i = 0; i < firstDay; i++) {
    dates.push(0);
  }
  for (let i = 0; i < lastDate; i++) {
    dates.push(i + 1);
  }
  for (let i = 0; i < dates.length; i += 7) {
    //store as 7-day blocks (weeks)
    separatedDates.push([
      dates[i],
      dates[i + 1],
      dates[i + 2],
      dates[i + 3],
      dates[i + 4],
      dates[i + 5],
      dates[i + 6],
    ]);
  }

  return (
    <div className="calendar-container">
      <h2 className="section-subtitle">
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            gap: "20px",
          }}
        >
          <div
            className="section-paragraph"
            style={{ cursor: "pointer" }}
            onClick={() => props.changeMonth("backward")}
          >
            {"<"}
          </div>
          {months[props.month].toUpperCase()} {props.year}
          <div
            className="section-paragraph"
            style={{ cursor: "pointer" }}
            onClick={() => props.changeMonth("forward")}
          >
            {">"}
          </div>
        </div>
      </h2>
      <div className="calendar-row">
        {days.map((day) => (
          <div className="calendar-week-box" key={day}>
            <div className="section-subtitle">{day}</div>
          </div>
        ))}
      </div>
      <div className="calendar-days-container">
        {separatedDates.map((dates) => (
          <div className="calendar-row" key={dates}>
            {dates.map((date) =>
              date === undefined || date === 0 ? (
                <div
                  style={{ width: "60px", height: "60px" }}
                  key={Math.random()}
                />
              ) : (
                <div
                  className="calendar-day-box"
                  style={{ cursor: "pointer" }}
                  id={date}
                  key={date}
                  onClick={() => props.onSelectDate(date)}
                >
                  <div className="section-paragraph">{date}</div>
                </div>
              )
            )}
          </div>
        ))}
      </div>
    </div>
  );
};
export default Calendar;