반응형
✔️ 필요성
classNames는 true/false boolean 값을 통해서 특정 스타일링을 할 지 말지 쉽게 분기하도록 도와주는 라이브러리이다. 컴포넌트의 props가 Active일때랑 Active가 아닐 때 보기 쉽게 CSS를 정리해보자
✔️ Props를 사용할 때
isActive의 값에 따라서 ? : 삼항연산자를 활용해서 다른 CSS를 줄 수도 있는데, 정확하게 isActive일 때 어떤 효과들이 들어갔는지 한 눈에 확인하기가 어렵다는 단점이 있다
const TabAnchor = styled.button<{ isActive: boolean }>`
color: ${({ theme, isActive }) =>
isActive ? theme.colors.white : "#333333"};
background-color: ${({ theme, isActive }) =>
isActive ? theme.colors.black : theme.colors.white};
border: ${(props) => (props.isActive ? `1px solid #333333` : `0px`)};
border-radius: ${(props) => props.isActive && "100px"};
font-size: calc(24 / 1920 * 100vw);
line-height: calc(28 / 1920 * 100vw);
font-weight: 600;
margin: calc(10 / 1920 * 100vw);
padding: calc(16 / 1920 * 100vw) calc(30 / 1920 * 100vw);
`;
✔️ className & classNames를 사용할 때
코드가 훨씬 깔끔해졌다
import styled from "@emotion/styled";
import classNames from "classnames";
const TabAnchor = styled.button`
color: ${({ theme }) => theme.colors.black};
background-color: ${({ theme }) => theme.colors.white};
border: 0px;
border-radius: 0px;
font-size: calc(24 / 1920 * 100vw);
line-height: calc(28 / 1920 * 100vw);
font-weight: 600;
margin: calc(10 / 1920 * 100vw);
padding: calc(16 / 1920 * 100vw) calc(30 / 1920 * 100vw);
&.isActive {
color: ${({ theme }) => theme.colors.white};
background-color: ${({ theme }) => theme.colors.black};
border: ${({ theme }) => `1px solid ${theme.colors.black}`};
border-radius: 100px;
}
`;
const Example = (tabIndex:number) => {
const tabList = ["A", "B", "C"];
return (
<Tab>
{tabList.map((item, i) => {
return (
<TabAnchor
key={i}
className={classNames({ isActive: tabIndex === i })}
>
{item}
</TabAnchor>
);
})}
</Tab>
);
};
반응형
'프론트엔드 앱 > Styled-Components' 카테고리의 다른 글
styled-component에서 Style Extend 안될 때 (0) | 2022.02.15 |
---|---|
styled-components에서 & 활용해서 CSS 분기 깔끔하게 하기 (0) | 2022.02.11 |
글자 길이가 넘칠 때 말줄임표(...)로 줄이기 (0) | 2022.01.03 |
react-navigation 하단줄 없애기 #borderBottom (0) | 2021.12.23 |
styled-components props와 theme을 동시 사용 (0) | 2021.12.13 |