Styled-Component에서 active 요소를 주고 싶을 때 className으로 제어해도 되고, props로 제어해도 된다.
props로 제어
isActive의 값에 따라서 ? : 삼항연산자를 활용해서 사용하는거라 한 눈에 확인하기가 어렵다는 단점이 있다.
const TabAnchor = styled.button<{ isActive: boolean }>`
border: ${(props) => (props.isActive ? `1px solid #333333` : `0px`)};
`;
className으로 제어
: 코드가 깔끔해진다.
import styled from "@emotion/styled";
const TabAnchor = styled.button`
border: 0px;
&.isActive {
border: ${({ theme }) => `1px solid ${theme.colors.black}`};
}
`;
const Example = (tabIndex:number) => {
const tabList = ["A", "B", "C"];
return (
<Tab>
{tabList.map((item, i) => {
return (
<TabAnchor
key={i}
className={ isActive: tabIndex === i }
>
{item}
</TabAnchor>
);
})}
</Tab>
);
};
출처
styled-components에서 classNames 사용해서 props에 따른 CSS 깔끔하게 사용하기
✔️ 필요성 classNames는 true/false boolean 값을 통해서 특정 스타일링을 할 지 말지 쉽게 분기하도록 도와주는 라이브러리이다. 컴포넌트의 props가 Active일때랑 Active가 아닐 때 보기 쉽게 CSS를 정리해
sezzled.tistory.com
'Development > React.js' 카테고리의 다른 글
Next에서의 에러 페이지 만들기 (0) | 2022.05.18 |
---|---|
next/image hostname error (0) | 2022.05.18 |
리엑트 폰트 버그 (0) | 2022.05.15 |
next - font를 글로벌 처리할 때 문제점 (0) | 2022.05.15 |
Prop `className` did not match. (0) | 2022.05.15 |