[DDD-Presen] react-calendar 라이브러리 스타일 오버라이딩하기

조민호·2024년 7월 2일
1


react-calendar 라이브러리로 달력을 사용하던 도중,

기본 스타일을 제거하고 현 프로젝트 디자이너의 요구사항대로

디자인을 커스텀 해야 하는 상황이 발생했다.

실제 react-calendar의 컴포넌트를 아래와 같이 호출하게 되면

import Calendar from 'react-calendar';

<Calendar />

이는 node_modules/react-calendar/src/Calendar.css 에 존재하는

아래와 같은 클래스명의 스타일이 기본적으로 적용된다

.react-calendar {
  width: 350px;
  max-width: 100%;
  background: white;
  border: 1px solid #a0a096;
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.125em;
}

여기서 node_modules/react-calendar/src/Calendar.css 에 존재하는 css를 내가 원하는 값들로 오버라이딩을 해서 사용해야 한다.



최대한 간단한 방법들을 찾아보았고 아래 2가지 방법을 알게 됐다.

1. 오버라이딩 전용 파일 생성하기

  1. CustomCalendar.scss 라는 오버라이딩 전용 파일을 생성한다

  2. 여기서 기존 node_modules 의 Calendar.css의 클래스에 대한

    오버라이딩을 진행한다

/* CustomCalendar.scss */

// 기존  node_modules 의 Calendar.css를 import
@import 'react-calendar/dist/Calendar.css'; 

// 원본 Calendar.css의 .react-calendar 오버라이딩
.react-calendar {
  width: 350px;
  max-width: 100%;
  background: white;
  border: 1px solid #a0a096;
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.125em;
}

// // 원본 Calendar.css의 .react-calendar__month-view__weekdays abbr 오버라이딩
.react-calendar__month-view__weekdays abbr {
  text-decoration: none;
  font-weight: 800;
}

개발자도구에서 리액트 캘린더 라이브러리의 내부 구조를 살펴보고

원하는 요소의 클래스명을 찾아서 설정해주면 원하는 스타일로

세부적인 커스텀을 할 수 있다

2. .module.scss 로 오버라이딩 하기

현재 프로젝트에서는 .module.scss 방식을 사용하고 있었다

이런 모듈 방식은 스타일의 범위를 로컬화하여 클래스명 충돌을 방지한다

.module.scss 파일에서 정의한 스타일은,

사용하고자 하는 컴포넌트에서 해당 .module.scss 파일을 import하고 사용하게 되면 클래스 이름에 빌드 과정에서 고유한 해시 값이 추가된다.

그래서 지금까지 전역 스타일의 오염 없이 컴포넌트별로 독립적인 스타일을 유지할 수 있었던 것이다.


그렇지만 .module.scss 파일에 오버라이딩 하고자 하는 라이브러리의 클래스네임을 사용해버리면
여기에도 마찬가지로 빌드 과정에서 해시 값이 추가돼버려서 기존 라이브러리의 클래스네임의 오바라이딩이 되지 않는다는 문제가 있다.


그러므로 :global 규칙을 사용하여 특정 스타일을 전역으로 설정하게

되면 CSS 모듈의 로컬 스코핑을 우회하는 방법을 사용할 수 있다.

@import 'react-calendar/dist/Calendar.css';

:global {
  .react-calendar {
    /* 전체 캘린더 스타일 변경 */
    border: 1px solid #ccc;
    font-family: Arial, sans-serif;
  }

  .react-calendar__month-view__days__day--weekend {
    /* 주말 날짜 스타일 변경 */
    color: red;
  }

  .react-calendar__tile:enabled:hover,
  .react-calendar__tile:enabled:focus {
    /* 타일 호버 및 포커스 스타일 변경 */
    background: #e6e6e6;
    color: #333;
    cursor: pointer;
  }
}
// CustomCalendar.tsx
import React from 'react';
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css'; // 기본 스타일을 먼저 import
import styles from './CustomCalendar.module.scss'; // :global로 오버라이딩한 스타일이 포함된 scss파일

const CustomCalendar = () => {
  return (
    <div className={styles.customCalendar}>
      <Calendar />
    </div>
  );
};

export default CustomCalendar;

나는 .module.scss를 피하기 위해 굳이 글로벌 스타일을 정의하는 2번 방법보다
차라리 오버리이딩 전용 .scss파일을 만드는것이 더 낫다고 판단돼서 1번 방법을 사용했다.

profile
웰시코기발바닥

2개의 댓글

comment-user-thumbnail
2024년 7월 4일

오버라이딩말고 오버헤드킥은 안되나요..?

답글 달기
comment-user-thumbnail
2024년 7월 12일

오... 오.. 오버라이딩.. 오..

답글 달기