✅ 원래 HTML / 리액트에서 CSS를 적용하던 방식은, HTML 선택자를 만들고, className이나 style을 부여하는 작업이 필요했다. 하지만 Styled Component를 사용하면 스타일도 컴포넌트로 관리 할 수 있다.
✅ 스타일링 된 컴포넌트를 사용하며, 컴포넌트 함수 내에 스타일을 쓸 필요가 없어 가독성이 훨씬 좋고 더불어 알아보기 쉬운 이름을 지을 수 있다.
//선언 방식
const Wrapper = styled.div`
display: flex;
height: 90vh;
flex-direction: row;
justify-content: center;
align-items: center;
`;
const Box = styled.div`
background-color: ${props => props.bgColor};
width: 100px;
height: 100px;
`;
---
function App() {
return (
<Wrapper>
<Box bgColor="teal" />
<Box bgColor="navy" />
</Wrapper>
);
}
Props
를 인자로 받아 Box
컴포넌트에 전달해줄 함수를 만들어 중복된 코드를 만들지 않고, 설정 가능한 Box
컴포넌트를 만들 수 있다.const Box = styled.div`
background-color: ${props => props.bgColor};
width: 100px;
height: 100px;
`;
const Circle = styled(Box)`
border-radius: 50px;
`;
Box
의 속성은 그대로 가져오되, 내가 추가하고 싶은 속성을 백틱 안에 적어준다.const Btn = styled.button`
color: white;
background-color: tomato;
border: 0;
border-radius: 15px;
`;
---
<Btn>Log in</Btn>
<Btn as="a" href="/">Log in</Btn>
const Input = styled.input.attrs({required: true, maxLength: 10 })`
background-color: purple;
color: white;
`;
---
<Input />
<Input />
<Input />
import styled, { keyframes } from "styled-components";
//keyframes helper (애니메이션 코드)
const animation = keyframes`
0% {
transform: rotate(0deg);
border-radius: 0px;
}
50% {
border-radius: 100px;
}
100% {
transform: rotate(360deg);
border-radius: 0px;
}
`;
---
//애니메이션을 받을 컴포넌트
const Box = styled.div`
width: 200px;
height: 200px;
background-color: violet;
animation: ${animation} 3s linear infinite;
`;
${animation}
형태로 불러와서, 적용시킬 수 있다.const Emoji = styled.span`
font-size: 20px;
`;
const Box = styled.div`
width: 200px;
height: 200px;
${Emoji} {
&:hover {
font-size: 30px;
}
}
`;
---
<Wrapper>
<Box>
<Emoji>🔮</Emoji>
</Box>
</Wrapper>
${Emoji}
형태로 컴포넌트를 불러와, Box 안에 있는 Emoji 컴포넌트를 선택하여 속성을 줄 수 있다.styled-components의 기본 개념에 대한 글입니다. 최신 버전에서 해당 내용이 변경되었을 수 있습니다. 부족하거나 맞지 않는 부분이 있다면, 댓글로 알려주세요!
styled-components: Basics 공식 문서 링크