Libraries/React
[React] 데이터 값에 따라 CSS 스타일 다르게 지정하기
dev-ini
2023. 12. 21. 20:18
728x90
데이터 값에 따라 CSS 스타일을 다르게 지정하는 법을 알아보자!
만들 예제의 완성본
"영업중"은 파란색, "영업종료"는 빨간색으로 뜬다.
1. 마크업을 한다.
List.jsx (리스트 페이지)
import "./List.css";
const List = () => {
const dummyList = [
{
id: 1,
title: "닭갈비",
state: "영업중"
},
{
id: 2,
title: "피자",
state: "영업종료"
},
{
id: 3,
title: "치킨",
state: "영업중"
},
{
id: 4,
title: "떡볶이",
state: "영업중",
},
{
id: 5,
title: "짜장면",
state: "영업종료",
},
];
return (
<div className="list">
<h1>음식점 리스트</h1>
<div className="list-container">
{dummyList.map((it) => (
<div key={it.id}>
<div className="list-box">
<div className="list-title">{it.title}</div>
<div className="list-state">{it.state}</div>
</div>
</div>
))}
</div>
</div>
);
};
export default List;
List.css (리스트 페이지 CSS)
.list {
margin-left: 100px;
margin-top: 100px;
}
h1 {
font-size: 30px !important;
display: flex;
margin-left: 80px;
}
.list-container {
width: 300px;
height: 100%;
background-color: rgb(38, 207, 196);
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
gap: 20px;
margin-top: 40px;
border: 2px solid #989898;
}
.list-box {
background-color: white;
width: 290px;
height: 80px;
display: flex;
flex-direction: column;
justify-content: center;
border-radius: 10px;
border: 1px solid #989898;
cursor: pointer;
gap: 7px;
padding-left: 10px;
}
.list-title {
font-size: 21px;
font-weight: 600;
}
.list-state {
font-size: 16px;
font-weight: 500;
}
2. 삼항연산자를 사용해서 조건에 따라 className이 다르게 지정되게 한다.
<div
className={`${["list-state"]} ${it.state === "영업종료" ? ["end"] : ""}`}
>
{it.state}
</div>
*참고) CSS Modules를 쓴다면, 아래와 같이 표기한다.
<div
className={`${styles["list-state"]} ${it.state === "영업종료" ? styles["end"] : ""}`}
>
{it.state}
</div>
List.jsx
import "./List.css";
const List = () => {
const dummyList = [
{
id: 1,
title: "닭갈비",
state: "영업중",
},
{
id: 2,
title: "피자",
state: "영업종료",
},
{
id: 3,
title: "치킨",
state: "영업중",
},
{
id: 4,
title: "떡볶이",
state: "영업중",
},
{
id: 5,
title: "짜장면",
state: "영업종료",
},
];
return (
<div className="list">
<h1>음식점 리스트</h1>
<div className="list-container">
{dummyList.map((it) => (
<div key={it.id}>
<div className="list-box">
<div className="list-title">{it.title}</div>
<div
className={`${["list-state"]} ${
it.state === "영업종료" ? ["end"] : ""
}`}
>
{it.state}
</div>
</div>
</div>
))}
</div>
</div>
);
};
export default List;
List.css
.list-state {
font-size: 16px;
font-weight: 500;
color: blue;
}
.list-state.end {
font-size: 16px;
font-weight: 500;
color: red;
}
완성본
728x90