우선 keyframes를 불러와준다.
import { keyframes } from "styled-components";
keyframes을 활용해 애니메이션을 정의한다.
적용할 스타일컴포넌트에 animation속성에 적용한다.
animation: ${animation} 1.5s linear infinite;
import styled, { keyframes } from "styled-components";
const Wrapper = styled.div`
display: flex;
`;
//styled-componets와 상관없고 그냥 CSS문법이다.
const animation = keyframes`
0% {
transform: rotate(0deg);
border-radius: 0px;
}
50% {
transform: rotate(360deg);
border-radius: 100px;
}
100% {
transform: rotate(0deg);
border-radius: 0px;
}
`;
const Box = styled.div`
height: 200px;
width: 200px;
background-color: tomato;
animation: ${animation} 1.5s linear infinite;
`;
function App() {
return (
<Wrapper>
<Box />
</Wrapper>
);
}
export default App;
모든 태그를 스타일 컴포넌트화 하지 않아도 간단한 문법으로 스타일컴포넌트 내의 Selector를 지정하여 속성을 부여해줄 수 있다.
const Box = styled.div`
height: 200px;
width: 200px;
background-color: tomato;
animation: ${animation} 1.5s linear infinite;
display: flex;
justify-content: center;
align-items: center;
//Box span{}과 같다.
span {
font-size: 50px;
//span:hover{}와 같다.
&:hover {
font-size: 80px
}
//span:active{}와 같다.
&:active {
opacity: 0;
}
}
`;
function App() {
return (
<Wrapper>
<Box>
<span>😃</span>
</Box>
</Wrapper>
);
}
위 예제의 span을 ${Emoji}로 변경해준다면 태그에 제한되지 않고 Emoji컴포넌트가 p,h1 등등 다른 태그로 변경되어도 속성들을 계속 적용되게 할 수 있다.
const Emoji = styled.span`
font-size: 50px;
&:active {
opacity: 0;
}
`;
const Box = styled.div`
height: 200px;
width: 200px;
background-color: tomato;
animation: ${animation} 1.5s linear infinite;
display: flex;
justify-content: center;
align-items: center;
${Emoji} {
&:hover {
font-size: 98px
}
}
`;
function App() {
return (
<Wrapper>
<Box>
<Emoji as="p">😃</Emoji>
</Box>
</Wrapper>
);
}