FrontEnd/Next.js
Next.js14) tailwind에서 동적 스타일링 제대로 구현하기
Bumang
2024. 7. 22. 11:34
삼항연산자를 이용한 동적 스타일링
테일윈드에서 동적으로 스타일링 할 때 아래와 같은 방법을 사용한다.
isRed의 값에 따라 bg-red-500이냐 bg-blue-500이냐를 가른다.
interface DynamicProps {
isRed: boolean;
}
export default function DynamicStyledButton({isRed}: DynamicProps) {
return (
<div className="flex items-center justify-center min-h-screen">
<button
onClick={() => setIsRed(!isRed)}
className={`px-4 py-2 text-white font-bold rounded ${isRed ? 'bg-red-500' : 'bg-blue-500'}`}
>
Click me!
</button>
</div>
);
}
class의 일부만 동적으로 관리할 수 없다.
그런데 많은 tailwind 입문자들이 실수하는 것이 아래와 같은 코드이다.
특정 클래스의 특정 부분만 수정하려고 하는 경우이다.
예를 들어 bg- 다음에 'red-500'이나 'blue-500'만 수정하려는 경우이다.
이런 경우 제대로 동작하지 않는다.
Tailwind CSS 클래스 이름을 동적으로 변경하는 방식으로 className 속성을 설정할 수 있지만,
템플릿 리터럴을 사용하는 방식으로는 직접적으로 동적 클래스를 생성할 수 없기 때문이다.
그 이유는 Tailwind CSS가 빌드 시 미리 정의된 클래스들만 포함하기 때문이라고 한다.
interface DynamicProps {
isRed: boolean;
}
export default function DynamicStyledButton({isRed}: DynamicProps) {
return (
<div className="flex items-center justify-center min-h-screen">
<button
onClick={() => setIsRed(!isRed)}
className={`px-4 py-2 text-white font-bold rounded bg-[${isRed ? 'red-500' : 'blue-500'}]`}
>
Click me!
</button>
</div>
);
}
조건이 3개 이상일 때 스위치문 쓰기
그러나 조건들이 너무너무 많다면 어떻게 해야될까?
삼항 연산자는 2가지 조건밖에 처리 못하니.. 여러 개일 때는 대안이 필요하다.
이럴 때는 if-else if문을 쓰거나 switch문을 통과하게 하여 동적으로 조건들을 변경할수도 있다.
interface DynamicProps {
isRed: boolean;
}
// switch문 예시
export default function DynamicStyledButton({isRed}: DynamicProps) {
const getColorClass = () => {
switch (color) {
case 'red':
return 'bg-red-500';
case 'blue':
return 'bg-blue-500';
case 'green':
return 'bg-green-500';
default:
return '';
}
};
return (
<div className={`px-4 py-2 text-white font-bold rounded ${getColorClass()}`}>
Dynamic Styled Component
</div>
);
}
// switch문 예시2
export default function DynamicStyledButton({color}: DynamicProps) {
switch (color) {
case 'red':
return 'bg-red-500';
case 'blue':
return 'bg-blue-500';
case 'green':
return 'bg-green-500';
default:
return '';
}
return (
<div className={`px-4 py-2 text-white font-bold rounded ${color}`}>
Dynamic Styled Component
</div>
);
}
혹은 그냥 인라인 css를 쓰기
width를 변화무쌍하게 바꿔야하는 경우, 스위치문으로도 역부족일 수 있다.
이런 경우를 위해 tailwind를 보완하기 위한 tailwind-merge와 clsx라는게 있다고는 들었는데,
아직 써본 적은 없다. tailwind 숙련도가 늘면 그때 써보도록 하겠다.
하여튼 이럴 때 추가적인 외부 라이브러리를 안 쓸거면 그냥 인라인 css로 조작하면 된다.
import styles from './DynamicWidthComponent.module.css';
export default function DynamicWidthComponent({ width }) {
return (
<div className={styles.container} style={{ width: `${width}%` }}>
Dynamic Width Component
</div>
);
}