프론트엔드 앱/Styled-Components

styled-components에서 & 활용해서 CSS 분기 깔끔하게 하기

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

 

✔️ 필요성

버튼 컴포넌트를 만들 때 사이즈나 컬러에 따라서 CSS 분기를 깔끔하게 해주고 싶을 때가 있다. 이 때는 className과 &를 활용해서 코드를 아주 깔끔하게 만들어줄 수 있다! 

 

 

✔️ 예시

import styled from "@emotion/styled";

const Container = styled.button`
  display: inline-block;
  flex: none;
  width: 100%;
  max-width: 100%;
  background: transparent;
  appearance: none;
  cursor: pointer;

  text-align: center;
  text-decoration: none;
  font-weight: 600;
  color: ${(props) => props.theme.colors.black};

  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  transition: background-color 0.1s cubic-bezier(0.45, 0, 0.55, 1);

  /* size */
  &.size--s {
    padding: 5px 30px;
    font-size: 16px;
    line-height: 24px;
  }

  &.size--m {
    padding: 9px 23px;
    font-size: 16px;
    line-height: 24px;
  }

  &.size--l {
    padding: 11px 23px;
    font-size: 18px;
    line-height: 28px;
  }

  /* color */
  &.color--blue {
    position: relative;
    background-color: ${(props) => props.theme.colors.point6A};
    border-color: ${(props) => props.theme.colors.point6A};
    color: ${(props) => props.theme.colors.white};
    &:hover {
      background-color: #096fcc;
    }
  }

  &.color--black {
    background-color: ${(props) => props.theme.colors.black};
    border-color: ${(props) => props.theme.colors.gray6e};
    color: ${(props) => props.theme.colors.white};
  }

  &.color--gray {
    background-color: ${(props) => props.theme.colors.grayEa};
    border-color: ${(props) => props.theme.colors.grayEa};
    color: ${(props) => props.theme.colors.black};
    &:hover {
      background-color: #bbbdc0;
    }
  }

  &.color--white {
    background-color: ${(props) => props.theme.colors.white};
    border-color: ${(props) => props.theme.colors.gray6e};
    color: ${(props) => props.theme.colors.gray6e};
    &:hover {
      background-color: ${(props) => props.theme.colors.grayEa};
    }
  }
`;
const Text = styled.p`
  display: inline;
  padding: 0;
  background: none;
  font-size: inherit;
  line-height: inherit;
  color: inherit;
  border: 0;
  &:hover,
  &:focus {
    background-color: inherit;
  }
`;

interface Props {
  size: "s" | "m" | "l";
  color: "black" | "gray" | "white" | "blue";
  text: string;
  onPress?: () => void;
}

const Button = ({ size, color, text, onPress }: Props) => {
  return (
    <Container className={`size--${size} color--${color} `} onClick={onPress}>
      <Text>{text}</Text>
    </Container>
  );
};

Button.displayName = "Button";
Button.defaultProps = {
  size: "l",
  color: "blue",
};

export default Button;

 

 

반응형