Styled Components의 가장 기본을 알아보자

function App() {
  return (
    <div style={{ display: 'flex' }}>
      <div style={{ backgroundColor: 'teal', width: 100, height: 100 }}></div>
      <div style={{ backgroundColor: 'tomato', width: 100, height: 100 }}></div>
    </div>
  );
}

위와 같은 코드를 아래처럼 바꿀 수 있다.

import styled from 'styled-components';

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

const BoxOne = styled.div`
  background-color: teal;
  width: 100px;
  height: 100px;
`;

const BoxTwo = styled.div`
  background-color: tomato;
  width: 100px;
  height: 100px;
`;

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

function App() {
  return (
    <Father>
      <BoxOne>
        <Text>Hello</Text>
      </BoxOne>
      <BoxTwo />
    </Father>
  );
}

export default App;

그러나 불만족스러운 부분이 있다!

반복되는 코드가 너무 많아!!

  1. props처럼 연결해서 쓰기 - props로 속성 전달하여 커스터마이즈할 수 있다.
  2. extend 해서 쓰기! styled(Box) 와 같이 작성하면 Box라는 컴포넌트를 extend 한다.
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: 50%;
`;

function App() {
  return (
    <Father>
      <Box bgColor="teal">
        <Text>Hello</Text>
      </Box>
      <Circle bgColor="tomato" />
    </Father>
  );
}

export default App;

As and Attrs

  1. 내가 지정한 스타일은 유지하고 싶으나, html 태그를 바꾸고 싶을 때!

🧐 이미 버튼으로 스타일드 컴포넌트 만들어 주었으나, a태그로 변경해주고 싶을 때! div를 h2로 변경하고 싶을 때!

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

<Btn>Log In</Btn>
<Btn as="a">Log In</Btn>

Untitled

  1. 어떤 컴포넌트에 동일한 속성을 적용해주고 싶을 때!

아래와 같이 attrs.를 작성하고 괄호 안에 객체 형태로 작성해주면 모두 동일하게 required가 된다.