Skip to content

Feat#2 jisoo/calendar#6

Open
seojisoosoo wants to merge 44 commits intomainfrom
feat#2-jisoo/calendar
Open

Feat#2 jisoo/calendar#6
seojisoosoo wants to merge 44 commits intomainfrom
feat#2-jisoo/calendar

Conversation

@seojisoosoo
Copy link
Copy Markdown
Contributor

@seojisoosoo seojisoosoo commented Jul 3, 2023

🔥 Related Issues

💙 작업 내용

  • 주어진 데이터를 기반으로 달력 구현
  • 해당하는 날짜를 클릭하면 일정을 추가할 수 있도록 구현

✅ PR Point

완전! 쓸애기 코드! 이렇게 할 수도 있겠구나 정도로만 봐주세요!!! 컴포넌트 분리도 너무너무 안 되었고, 라이브러리를 뜯어고치느라고 애만 먹은 코드입니다ㅠㅠ 쓸애기!

react-calendar react-ios-time-picker 라이브러리 이용했습니다

components/jisoo/JisooCalendar.tsx

  • Date 객체를 string 형식으로 변경할 때에는 moment(value).format("YYYY-MM-DD") 와 같은 방법을 사용했습니다. toIOString()메소드를 이용해보기도 했는데, 자꾸 하루 전 날짜로 찍히더라고요...! 그래서 moment 이용했습니다! (import moment from "moment"; 필요!)

  • react-calendar에서 한칸한칸을 tile이라고 하더라고요! 내가 가진 수업데이터를 map돌리고 그 중에서도 날짜가 현재 날짜와 동일하면 html이라는 배열에 해당 태그를 넣어주는 방식으로 구현하였습니다.

 tileContent={({ date, view }) => {
            let html: Element[] = [];
            {
              classData.map(({ id, student, times, color }: calendarDatatTypes) => {
                times.map(
                  ({ dates, time }) =>
                    dates === moment(date).format("YYYY-MM-DD") &&
                    html.push(
                      <Box key={id} $color={color}>
                        <p>{student}</p>
                        <p>{time}</p>
                      </Box>,
                    ),
                );
              });
            }
  • 시간을 선택하는 로직은 아래와 같아요! 추가된 새로운 시간이 newTimeData이고, 원래의 시간을 map을 돌려서 읽어온 뒤 originTimeDatas에 할당했어요. 입력된 학생의 수업이 더 추가된 로직이라서 input으로 입력받은 학생의 이름과 동일하면, times의 데이터가 추가되는 방식으로 구현했습니다! 처음에는 삼항연산자가 아닌 &&연산자만 썼는데, false인 경우 로직이 없다고 오류떠서 아래와 같이 삼항연산자로 표기했어요!
function handleSaveTimes() {
    handleCloseModal();
    const newTimeData = startTimeValue.split(" ")[0] + "~" + endTimeValue.split(" ")[0];
    const originTimeDatas = classData
      .map(({ student, times }) => student === studentName && times)
      .filter((time) => time !== false)[0];

    setClassData(
      classData.map((data) =>
        data.student === studentName
          ? {
              ...data,
              times: [...originTimeDatas, { dates: moment(value).format("YYYY-MM-DD"), time: newTimeData }],
            }
          : data,
      ),
    );
  }
  • ios-time-picker에는 한글로 변환하는 기능이 없는 것 같아요..... 그래서 아래와 같은 코드로 직접 변환해주었습니다ㅜㅜ불편...
스크린샷 2023-07-04 오전 7 15 37
  function checkTimeValue(time: string) {
    const hour = time.split(" ")[1];
    const realTime = time.split(" ")[0];

    return hour === "AM" ? "오전 " + realTime : "오후 " + realTime;
  }

index.html

  • 마찬가지로 AM, PM을 변경하고 싶어서 이렇게 도전했는데 안 먹네요ㅠ
  <script>
     window.onload = function () {
       document.querySelector(".react-ios-time-picker-cell-inner-hour-format-selected").innerHTML = "오전";
       const sections = document.querySelectorAll(".react-ios-time-picker-cell-inner-hour-format");

       console.log(sections);
       console.log(sections.length);
       for (let i = 0; i < sections.length; i++) {
         if (i === 0) {
           let item = sections.item(i);

           item.innerHTML = "오전";
         }
       }
     };
   </script>

😡 Trouble Shooting

  • react-calendar 라이브러리는 컴포넌트 안에 선언이 되는데, react-ios-time-picker는 컴포넌트 바깥에 선언이 되어서, react-ios-time-picker를 커스터마이징할 때에는 index.css파일을 만들었어요ㅜㅜ 이게 무슨 말이냐하면!! react-ios-time-picker라이브러리를 통해 생성되는 ui들은 <div id="root"> 바깥에 생성이 된다는 뜻입니다,,,기본적으로 <div id="root"> 안쪽에 모든 로직이 생성되는 리액트의 방식을 거스르는 느낌이었어요...
  • 데이터를 주고받기 위해서는 a라는 날짜에 직결되는 b라는 시간이 필요하더라고요... 그러니까, 2023-7-4이라는 날짜에 직결되는 12:00~13:00라는 시간이 필요했어요! 그래서 아래와 같이 데이터 타입을 변경하였습니다...
  • 뿐만 아니라, 학생 개개인에게 색상코드가 필요한데, 학생마다 색깔이 달라야하니까, 이것도 서버에서 보내주면 좋겠다는 생각이 들어서 추가했어요!
import { calendarDatatTypes } from "../../type/jisoo/calendarDataTypes";

export const CAELENDAR_DATA: calendarDatatTypes[] = [
  { id: 1, student: "은빈", times: [{ dates: "2023-07-20", time: "09:00~10:00" }], color: "#FFC81E" },
  { id: 2, student: "혜인", times: [{ dates: "2023-07-21", time: "10:00~11:00" }], color: "#EB0000" },
  { id: 3, student: "성경", times: [{ dates: "2023-07-06", time: "09:00~10:00" }], color: "#FFB6C1" },
  {
    id: 4,
    student: "희정",
    times: [
      { dates: "2023-07-06", time: "19:00~20:00" },
      { dates: "2023-07-16", time: "18:00~19:00" },
    ],
    color: "#7B68EE",
  },
  {
    id: 5,
    student: "지수",
    times: [
      { dates: "2023-07-06", time: "13:00~14:00" },
      { dates: "2023-07-13", time: "13:00~14:00" },
      { dates: "2023-07-20", time: "13:00~14:00" },
      { dates: "2023-07-27", time: "13:00~14:00" },
    ],
    color: "#5F9EA0",
  },
];

👀 스크린샷 / GIF / 링크

2023-07-04.7.05.04.mov

📚 Reference

react-ios-time-picker

@seojisoosoo seojisoosoo self-assigned this Jul 3, 2023
@seojisoosoo seojisoosoo added feat-function 기능구현했어요 feat-UI UI 만들었어요 지수 지수 담당 labels Jul 3, 2023
@seojisoosoo seojisoosoo added this to the 지수 캘린더 milestone Jul 3, 2023
@seojisoosoo seojisoosoo marked this pull request as ready for review July 3, 2023 22:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat-function 기능구현했어요 feat-UI UI 만들었어요 지수 지수 담당

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ Jisoo ] - 캘린더 구현

1 participant