styled-components

Sammy·2022년 6월 2일
0

styled-components는 css를 JavaScript로 사용할 수 있게 해준다.
또, 컴포넌트 안에서 사용되기 때문에 css가 중첩되지 않는다.

App.js

import styled from "styled-components";

const Father = styled.div`
  display: flex;
`;

const Box = styled.div`
  background-color: ${(props) => props.bgColor};
  width: 100px;
  height: 100px;
`;

const Text = styled.span`
  color: white;
`;

const Circle = styled(Box)`
  border-radius: 50px;
`;
function App() {
  return (
    <Father>
      <Box bgColor="teal" />
      <Circle bgColor="tomato" />
    </Father>
  );
}

export default App;

위 코드처럼 동일한 컴포넌트를 사용하지만 한가지 속성만 바꾸고 싶을 땐 props를 사용하면 된다.
Box라는 컴포넌트에 bgColor라는 props를 부여해줌으로서 같은 컴포넌트로 다른 색상을 사용할 수 있게 된다.
또 Circle는 Box컴포넌트의 속성을 그대로 가져오고 거기에 스타일을 추가해 확장시킨 컴포넌트이다.

as

const Father = styled.div`
  display: flex;
`;

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

function App() {
  return (
    <Father>
      <Btn as="header">Log in</Btn>
      <Btn as="a" href="/">
        Log in
      </Btn>
    </Father>
  );
}

Btn컴포넌트는 button태그로 만들어진 컴포넌트이다.
근데 Btn의 속성은 쓰고 싶지만 button이 아닌 다른 태그로 사용하고 싶을 때 'as'를 사용하면 된다.
렌더함수에 Btn을 사용하고 as="header"를 쓰면 Btn의 스타일은 그대로 가져오지만 태그는 header로 바뀌게 된다.

attrs 속성 추가하기

const Father = styled.div`
  display: flex;
`;

const Input = styled.input.attrs({ required: true })`
  background-color: tomato;
`;

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

각 Input에 required라는 속성을 추가하고 싶을 때 하나하나 작성하지 않고
컴포넌트에서 attrs를 사용하면 좀 더 간결한 코드를 만들 수 있다.

Animations and Pseudo Selectors

const Wrapper = styled.div`
  display: flex;
`;

const rotationAnimation = keyframes`
  0%{
    transform: rotate(0deg);
    border-radius:0px;
  }
  50%{
    transform: rotate(360deg);
    border-radius:100px; 
  }
  100%{
    transform: rotate(0deg);
    border-radius:0px;
  }
`;
const Box = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  display: flex;
  justify-content: center;
  align-items: center;
  animation: ${rotationAnimation} 1s linear infinite;
  span {
    font-size: 36px;
    &:hover {
      font-size: 60px;
    }
    &:active {
      opacity: 0;
    }
  }
`;
function App() {
  return (
    <Wrapper>
      <Box>
        <span>🤩</span>
      </Box>
    </Wrapper>
  );
}

rotationAnimation이라는 컴포넌트를 만든다. 이 컴포넌트는 styled-component를 사용하는 건 아니다.
CSS의 keyframes를 이용해서 50%가 됐을때 원을 만들고 0%,100%일 때 다시 네모로 되돌아간다.
이걸 Box컴포넌트에 animation을 이용하여 적용시킬 수 있다.
또 렌더함수내에서 Box 안에 span태그를 만들었는데 이 span도 Box컴포넌트 안에서 스타일을 추가할 수 있다.
&:hover 과 &:active 는 span:hover , span:active 와 같은 의미이다.

profile
Web Developer

0개의 댓글