프론트엔드 앱/Styled-Components

styled-components에서 classNames 사용해서 props에 따른 CSS 깔끔하게 사용하기

세리둥절 2022. 2. 11. 19:03
반응형

 

✔️ 필요성

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>
  );
};
반응형