styled-components(with React) 코드 재사용 기능

이지원·2022년 1월 14일
1

style-components

목록 보기
2/3

기존 코드의 문제점


const Father = styled.div`
  display: flex;
`;
const Child1 = styled.div`
  background-color: black;
  width: 100px;
  height: 100px;
`;
const Child2 = styled.div`
  background-color: yellow;
  width: 100px;
  height: 100px;
`;


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

위와 같이 styled-components를 이용해서 컴포넌트를 선언하였을 때,
Child1 컴포넌트와 Child2 컴포넌트는 배경색상 말고는 동일한 css속성을 가지고 있다.
일반적인 css라면 배경색상이 다르기 때문에 위와같이 나눠줄 수 밖에없다.

Styled-components 라면?😎 Props!

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

function App() {
  return (
    <Father>
      <Child bgColor="black" />
      <Child bgColor="red" />
    </Father>
  );
}

위 처럼 사용할 수 있다. 컴포넌트 개념이기때문에 react에서 사용하는 props로 데이터를 넘겨줄 수 있기 때문에 불필요한 코드의 중복을 줄일 수 있다.

styled-components 상속기능

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

const ChildCircle = styled.div`
  background-color: ${props => props.bgColor};
  width: 100px;
  height: 100px;
  border-radius: 10px;
`;

function App() {
  return (
    <Father>
      <Child bgColor="black" />
      <ChildCircle bgColor="red" />
    </Father>
  );
}

ChildCircle 이라는 컴포넌트를 새로 만들었을때,
Child와 중복되는 코드를 발견할 수 있다.
위 점을 고려하여 styled-components의 상속기능을 이용해보자.

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

const ChildCircle = styled(Child)`
  border-radius: 10px;
`;

기존에 사용하던 styled.(Html 태그)대신 (선언한 컴포넌트이름)이 들어갔다.
이 뜻은 ChildCircle 컴포넌트는 Child에서 선언한 css속성을 전부다 상속한다는 개념이다.
즉 ChildCircle 컴포넌트는 Child에서 상속받은 css + ChildCircle 만의 css를 적용한 컴포넌트가 된것이다.
최종코드.

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

const ChildCircle = styled(Child)`
  border-radius: 10px;
`;

export default function App() {
  return (
    <Father>
      <Child bgColor="black" />
      <ChildCircle bgColor="red" />
    </Father>
  );
}
profile
안녕하세요 피드백은 언제나환영입니다.

0개의 댓글