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;
반복되는 코드가 너무 많아!!
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;
🧐 이미 버튼으로 스타일드 컴포넌트 만들어 주었으나, 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>
아래와 같이 attrs.를 작성하고 괄호 안에 객체 형태로 작성해주면 모두 동일하게 required가 된다.