프론트엔드/TS

styled-components 이용하기

거북목을 가진 김기린 2022. 6. 7. 19:34
728x90
반응형
const Box1 = styled.div`
    width: 100px;
    height: 100px;
`;

const Box2 = styled(Box1)`
	border-radius: 50px;
`;
const Box1 = styled.div`
	width: 100px;
    height: 100px;
`;

const Box2 = styled.div`
	width: 100px;
    height: 100px;
    border-radius: 50px;
`;

1. 상속

위의 Box1, Box2는 border-radius를 제외한 코드의 내용은 동일하다.

상속을 사용하면 반복을 제거할 수 있다.

 

const Btn = styled.button`
   color: white;
   background-color: tomato;
   border-radius: 15px;
   border: 0px;
`;

function App() {
  return (
    <Father>
      <Btn>log in</Btn>
      <Btn as='a' href='/'>log in</Btn>
    </Father>
  );
}

2.  HTML 태그 변경(as)

Btn은 button 태그이지만 as을 이용하면 다른 HTML 태그로(a) 변경이 가능하다.

 

 const Input = styled.input.attrs({required:true, minLength:10})`
   background-color: blue;
   color: white;
   width: 100px;
   height: 30px;
`;

function App() {
  return (
    <Father>
      <Input />
      <Input />
    </Father>
  );
}

3. 속성값 생성(attrs)

여러 Input이 있으며 속성 required와 minLength을 반복해서 작성을 할 때

attrs를 이용한다면 속성값을 제어할 수 있기 때문에 유용하다.

 

const Animation = keyframes`
  0%{
    border-radius: 0px;
    transform:rotate(0deg);
  }
  50%{
    border-radius: 100px;
    transform:rotate(360deg);
  }
  100%{
    border-radius: 0px;
    transform:rotate(0deg);
  }
`;

const Emoji = styled.span`
  font-size: 30px;
`;

const Box = styled.div<Props>`
  background-color: ${(props => props.bgColor)};
  width: 100px;
  height: 100px;
  animation: ${Animation} 3s linear infinite;
  
  display: flex;
  justify-content: center;
  align-items: center;
  ${Emoji}{
    &:hover{
      background-color: red;
   }
  }
`;

function App() {
  return (
    <Father>
      <Box bgColor='yellow'>
        <Emoji>😊</Emoji> 
      </Box>
    </Father>
  );
}

4. 애니메이션(keyframes) & pseudo selector

animaition 선언은 위와같이 하며, 필요한 컴포넌트 내에 ${애니메이션}을 통해 적용을 해준다.

또한 코드의 반복성을 줄이기 위해 ${Emoji}{ &:hover{ ... } }를 이용해주면 좋다.

728x90
반응형