본문 바로가기
css

module.scss 를 활용해 다양한 styling 진행하기

by ccaeml 2024. 2. 28.

모듈사스를 이용해서 컴포넌트에 다양한 상황에 맞는 스타일링을 적용시켜봤다. 다양한 유형의 class 를 만들어 놓은 뒤 컴포넌트의 Prop 을 통해 type 을 통해 유형을 할당하는 구조를 취하도록 만들었다. 'npx create-next-app' 을 통해 생성한 애플리케이션이 기본적으로 module.scss 를 사용하기에 여러모로 도움이 될 것 같다. 아래의 상황을 이해하고 2가지를 알아가자!

 

[ 이글의 목표 ]

1. Component 의 type 설정(@extends 문법활용)

2. 컴포넌트에서 유형을 할당해 사용하는 방법


 

문제상황

사용하는 html 요소는 같은데 페이지 별로 미묘하게 styling 이 달라져야한다. {children} 을 통해 스타일링 제어권을 넘겨줄 수 있지만, 미리미리 만들어두는게 필요한 상황(type 이 필요한 이유)이 있을 수 있다. 문제는 후자를 가정한다. (둘을 혼용해서 사용하지 않을까?)

 

=> 구체적으로, 지표정보를 표현할 카드를 만들 때 Mainpage, Dashboard 페이지 별로 type 을 할당한 후 활용하는 구조를 만들 계획이다.

 

1. Module.scss 에서 타입 지정

$tablet: 1023px;
$mobile: 650px;

// desktop + laptop 공통 스타일
.IndicatorCardBase {
	width: 230px;
	height: 250px;
	... 
}

// mainpage type 
.IndicatorCardMainPage {
    // 공통스타일 @extend 를 통해 type 에 적용
	@extend .IndicatorCardBase;

	// page 별로 다른 반응형처리 
	@media (max-width: $tablet) {
		width: 30%;
		background: #ccc;
		padding: 15px;
	}

	@media (max-width: $mobile) {
		width: 100%;
		background: gray;
		padding: 10px;
	}
}

// dashboard type
.IndicatorCardDashboard {
    // 공통스타일 @extend 를 통해 type 에 적용
	@extend .IndicatorCardBase;
	height: 30vh;

	// page 별로 다른 반응형처리 
	@media (max-width: $tablet) {
		background: blue;
		padding: 15px;
	}

	@media (max-width: $mobile) {
		background: gray;
		padding: 10px;
	}
}

 

 

2. 컴포넌트 생성

import clsx from 'clsx';
import styles from './IndicatorCard.module.scss';

function checkingPageTypeAndModifyClassName(pageType: string) {
	let className = 'defaultClassName';
	if (pageType === 'main') {
		className = 'IndicatorCardMainPage';
	} else if (pageType === 'dashbaord') {
		className = 'IndicatorCardDashboard';
	}

	return className;
}

export default function IndicatorCard({ otherProps, pageType }: IndicatorCardProps) {
	const CardClassName = checkingPageTypeAndModifyClassName(pageType);
    
	return (
		<div className={clsx(styles[CardClassName])}>
			...
		</div>
	);
}

 

 

3. 컴포넌트 활용

import IndicatorCard from 'IndicatorCard.tsx';

export default function Pages({}) {
  	return (
		<IndicatorCard otherProps={...} pageType={'main'}/>
	);
}

 

 

- 위 코드는 Component.module.scss 을 간추렸다. 아래의 3개의 단계를 거쳐 생성하며 3 의 과정은 귀찮으면 안해도 문제없다. 

1. .IndicatorCardMainPage class 생성하기

2. .IndicatorCardDashboard class 생성하기

3. 공통된 부분은 @extend 를 활용해 중복제거

 

=> 이 과정을 통해 page 별로 필요한 세밀한 styling 을 미리 만들어 유지보수성을 높였다.