⭕styled-components란 Javascript 파일 내에서 CSS를 사용할 수 있게 해주는 대표적인 CSS-in-JS 라이브러리로 React 프레임워크를 주요 대상으로 한 라이브러리이다.
$ npm install --save styled-components
// styled-components를 사용 하기 위해서는 import 해줘야 함 import styled from "styled-components"; // 변수 = styled.HTML태그명 `css 언어`; const Father = styled.div` background-color: tomato display: flex; `; function App() { return ( <Father /> ); } export default App;
⭕컴포넌트에 prop을 설정하여 background-color: ${(props) => props.bgColor}; 와 같은 동적인 코드를 만들 수 있다.
const Circle = styled(Box)` border-radius: 50px; `; const Circle = styled.div` background-color: ${(props) => props.bgColor}; width: 100px; height: 100px; border-radius: 50px `; 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="tomato" /> </Father> ); } export default App;
⭕'as'
HTML 태그를 바꿔준다.
<Btn as="a" href="/">Log in </Btn>
⭕attrs
컴포넌트에 기본 값을 줄 수 있다.
const Input = styled.input.attrs({required : true})` background-color : "tomato" `;
import styled from "styled-components"; const Father = styled.div` display: flex; `; const Btn = styled.button` background-color : tomato border-radius: 15px; color : white `; const Input = styled.input.attrs({required : true})` background-color : tomato `; function App() { return ( <Father> <Btn as="a" href="/">Log in</Btn> <Input /> <Input /> <Input /> </Father> ); } export default App;