본문 바로가기
부트캠프교육중/react

[React] styled component에서 props 활용하기

by 뭉지야 2023. 8. 17.
728x90

# styled component에서 props활용하기

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></BoxTwo> 
    </Father>
  );
}

export default App;

위의 BoxOne 코드와 BoxTwo코드가 색만 다르고 다른 부분은 다 같으므로

코드를 깔끔하게 바꿔보자.

 

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;
`;

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

export default App;

 

이렇게 styled component에서도 props를 이용할수있다.

 


# styled component 활용하여 컴포넌트 확장하기.

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

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

저렇게 코드가 중복으로 나타날때  Circle의 코드를 간결하게 정리해줄수있다.

 

border-radius만 추가된거니까

 

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

const Circle = styled(Box)`
  border-radius: 50px;
`;

이렇게하면 Circle은 Box의 모든 걸 상속받는다.

728x90