Next.js 13에서 tailwindcss를 사용하여 동적 스타일링 컴포넌트 구성하기
Next.js 2023. 8. 27. 11:59회사에서는 react.js + styled-component를 활용한 아토믹 디자인 패턴을 사용하고 있어서, 커스텀 컴포넌트를 구성하고 스타일 속성을 객체 형태로 생성하여 이를 활용하고, 문맥에 맞게 디자인 속성 값을 다양하게 적용하여 컴포넌트의 재사용성과 조합성을 강화하고 있다.
하지만 tailwindcss에서는 동적으로 className을 변경하여 적용하는 것을 권장하고 있지않다. 예를 들면 다음과 같은 코드 구성을 사용할 수 없다는 것이다.
TestComponent에서와 같이 colorLevel을 전달받아 bg-red-{colorLevel}의 값을 동적으로 생성할 수 없다.
const TestComponent = ({ colorLevel }: { colorLevel: String }) => {
const className = `w-32 h-32 bg-red-${colorLevel}`;
return <div className={className}></div>;
};
export default TestComponent;
이는 tailwindcss 에서도 안내하고 있는 사항으로 아래 글을 통해 확인할 수 있다.
https://tailwindcss.com/docs/content-configuration#dynamic-class-names
Content Configuration - Tailwind CSS
Configuring the content sources for your project.
tailwindcss.com
해당 내용은 아래와 같이 활용하는 예시를 통해 동적으로 스타일링을 할 수 없는걸 확인할 수 있다.
import Section from "@/src/components/atoms/Section";
import TestComponent from "@/src/components/atoms/TestComponent";
export default function Page() {
return (
<Section>
<TestComponent colorLevel="500" />
</Section>
);
}
TestComponent에 전달한 500으로 bg-red-500이 최종적으로 적용되었지만 컴파일 후 에는 적용되지 않음을 확인할 수 있다.
이 문제를 해결하기 위해서는 tailwindcs의 safelisting-classes에 사용할 tailwindcss 속성을 미리 장석하면 컴파일시, 해당 속성은 제거하지 않아 사용할 수 있게된다.
tailwindcss는 컴파일 시 사용하지 않는 css속성들은 제거되어 동적으로 사용하는 경우에는 해당 값이 tailwindcss에 유효하더라도 이미 해당 css속성은 사용하지 않는 걸로 판단해 컴파일 이후에는 적용할 수 없게된다.
https://tailwindcss.com/docs/content-configuration#safelisting-classes
Content Configuration - Tailwind CSS
Configuring the content sources for your project.
tailwindcss.com
이를 쉽게 말하자면 TestComponent에 500을 넘겨주어 최종적으로 bg-red-500을 사용하고자 했지만 tailwindcss가 컴파일 할 때는 bg-red-500가 사용되지 않아 해당 속성을 사용할 필요가 없다고 판단, 이를 제거하게 된다. 따라서 최종적으로 브라우저에서 랜더링 후, bg-red-500을 사용할 때는 css가 없어서 적용되지 않는다.
tailwindcss에서 동적으로 css를 적용하기 위해서는 아래 방식을 사용할 수 있다.
const TestComponent = ({ error }: { error: Boolean }) => {
const className = `
w-32 h-32
${error ? "bg-red-500" : "bg-white"}
`;
return <div className={className}></div>;
};
export default TestComponent;
tailwindcss의 css className명을 동적으로 생성하는 것이 아닌, Props에 따라 사용할 css className를 선택하여 사용할 수 있도록 한다.
import Section from "@/src/components/atoms/Section";
import TestComponent from "@/src/components/atoms/TestComponent";
export default function Page() {
return (
<Section>
<TestComponent error={true} />
<TestComponent error={false} />
</Section>
);
}
fsd 아키텍처을 사용해보자 1 - memo app (0) | 2025.03.22 |
---|---|
next.js with bun (0) | 2024.11.21 |
로그인 페이지 구성 with TailwindCSS (0) | 2023.11.07 |
Next.js 개요 및 프로젝트 구조 (2) | 2023.08.28 |
Next.js 13에서 tailwindcss가 적용되지 않는 오류 해결 (1) | 2023.08.26 |