미누에요

[React] module scss 에서 변수 사용하기 본문

React

[React] module scss 에서 변수 사용하기

미누라니까요 2025. 5. 13. 21:35
728x90
반응형
SMALL

현재 개인적으로 공부 차 프로젝트를 진행 중인데, 이 프로젝트 중 Button 컴포넌트를 제작하고 있었다.

 

현재 TypeScript + module.scss를 사용하고 있는데, tsx 파일에서 특정 색상값을 변수 형식으로 넘겨주고, scss 파일에서 해당 값을 사용하고 싶었다.

즉, tsx에서 변수를 넘겨받아 scss에서 사용하고 싶었던 것이다.

 

const ImageCircle = styled.div`
    --size: ${props => props.size}px;
    width: var(--size);
    height: var(--size);
    border-radius: var(--size);

    background-image: url(${props => props.src});
    background-size: cover;
    margin: 4px;
`;

export default Image;

이전에 위 코드처럼 styled-component에서 변수를 사용한 적이 있었기에, module scss에서도 사용해보았다.

(위 코드는 https://cheri.tistory.com/159)

 

 

Button.tsx

import styles from "./button.module.scss";

type ButtonProps = {
	text: string;
	color?: string;
	fontColor?: string;
	onClick: () => void;
	disabled?: boolean;
};

function Button({ text, color, fontColor, onClick, disabled }: ButtonProps) {
	return (
		<div className={styles.container}>
			<button
				disabled={disabled}
				onClick={onClick}
				style={
					{
						"--button-color": disabled ? "#EDF2F7" : color,
						"--font-color": disabled ? "#A0AEC0" : fontColor,
					} as React.CSSProperties
				}
			>
				{text}
			</button>
		</div>
	);
}

export default Button;

 

우선 Button.tsx 코드를 보면 style 속성에 객체 타입으로 변수 두 개를 넘겨준다.

{
    "--button-color": disabled ? "#EDF2F7" : color,
    "--font-color": disabled ? "#A0AEC0" : fontColor,
} as React.CSSProperties

 

위와 같이 넘겨줄 변수 이름, 그리고 값을 객체로 감싸고, as React.CSSProperties로 타입을 정해주게 되면 module scss 파일에서 해당 변수명으로 값들을 사용할 수 있게된다!!

 

joinPage.module.scss

.container {
	width: 100%;
	button {
		border: 1px solid #e2e8f0;
		border-radius: 8px;
		padding: 0.8em 1.2em;
		width: 100%;
		background-color: var(--button-color, white);
		color: var(--font-color, black);
	}
}

 

이 코드에서 보면 var()를 사용해서 변수를 사용하는 것을 볼 수 있다. 두 번째 인자는 기본값이다.

 

 

결과 사진

 

 

결론적으로, module scss에서 변수를 사용하려면 , tsx 파일에서 객체 형식으로 변수 및 값을 입력하고, as React.CSSProperties로 정한다면 해당 값들을 사용할 수 있게된다.
728x90
반응형
LIST

'React' 카테고리의 다른 글

[React] Props  (0) 2024.02.12
[React] 컴포넌트 (Components)  (0) 2024.02.12