styled-component
를 사용해서 색상이 다른 Box 두개를 만들어보겠다.
import styled from "styled-components";
const Father = styled.div`
display: flex;
`;
const Box1 = styled.div`
background-color: teal;
width: 100px;
height: 100px;
`;
const Box2 = styled.div`
background-color: orange;
width: 100px;
height: 100px;
`;
function App() {
return (
<Father>
<Box1 />
<Box2 />
</Father>
);
}
export default App;
정상적으로 작동하지만, Box1
과 Box2
에서 background-color
를 제외하고는 모든 코드가 일치하는 것을 볼 수 있다. 코드를 간결하게 하기 위한 방법이 필요하다.
${(props) => props.name}
props
를 이용해서 코드를 더 간결하게 할 수 있다.
import styled from "styled-components";
const Father = styled.div`
display: flex;
`;
const Box = styled.div`
background-color : ${(props) => props.bgColor};
width: 100px;
height: 100px;
`
function App() {
return (
<Father>
<Box bgColor="teal" />
<Box bgColor="orange" />
</Father>
);
}
export default App;
똑같이 정상적으로 동작하는 것을 확인할 수 있다.
Box
라는 컴포넌트 안에 background-color : ${(props) => (props.bcColor}
형식으로 props
를 집어넣어 원하는 속성만 변경할 수 있다.
Box
와 다른 속성은 같고 border-radius
가 다른 Circle
도형을 만들어보려고 한다.
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 Circle = styled.div`
background-color: ${(props) => props.bgColor};
width: 100px;
height: 100px;
border-radius: 50px;
`;
function App() {
return (
<Father>
<Box bgColor="teal" />
<Circle bgColor="gray" />
</Father>
);
}
export default App;
마찬가지로 정상적으로 동작하지만, 우리는 이 코드를 더 간결하게 만들 수 있지 않을까?
styled(Name)
Circle
컴포넌트 안에 Box
컴포넌트 속성을 담아줄 수 있다.
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 Circle = styled(Box)`
border-radius: 50px;
`;
function App() {
return (
<Father>
<Box bgColor="teal" />
<Circle bgColor="orange" />
</Father>
);
}
export default App;
Circle
에 styled.div
를 입력하는 대신 styled(Box)
처럼 가져올 컴포넌트를 입력하면 Box
의 속성을 그대로 갖다 쓸 수 있다.