Front-End/React(비공)

[React] styled components 2. animation, selector

리리히히 2024. 3. 20. 11:02
반응형

 

🔎 전체코드 한번에 보기

import styled, {keyframes} from "styled-components"

const Title = styled.h1`
 color: tomato;
`

const Wrapper = styled.div`
  display: flex;
  height: 100vh;
  width: 100vw;
`;

const rotateAnimation = keyframes`
  from {
    transform: rotate(0deg);
    border-radius: 0px;
  }
  to {
    transform: rotate(360deg);
    border-radius: 100px;

  }
`;

const Emoji = styled.span`
  font-size: 36px;
`;

const Box = styled.div`
  width: 200px;
  height: 200px;
  display: flex;
  background: tomato;
  justify-content: center;
  align-items: center;
  animation: ${rotateAnimation} 1s linear infinite;
  ${Emoji}{
    font-size: 36px;
    &:hover {
      font-size: 50px;
    }
    &:active {
      opacity: 0;
    }
  }
`


function App() {
  return (
    <Wrapper>
      <Box>
        <Emoji>😊</Emoji>
      </Box>
      <Emoji>❤️</Emoji>
    </Wrapper>
  );
}

export default App;

 


 

🔎 코드 쪼개서 설명

import styled, {keyframes} from "styled-components"
  • keyframes를 쓰기 위해서는 제일 상단에 helper function을 추가

 

const rotateAnimation = keyframes`
  from {
    transform: rotate(0deg);
    border-radius: 0px;
  }
  to {
    transform: rotate(360deg);
    border-radius: 100px;
  }
`;
  • rotateAnimation이라는 keyframes 애니메이션 컴포넌트를 생성

 

const Emoji = styled.span`
  font-size: 36px;
`;

const Box = styled.div`
  width: 200px;
  height: 200px;
  display: flex;
  background: tomato;
  justify-content: center;
  align-items: center;
  animation: ${rotateAnimation} 1s linear infinite;
  ${Emoji}{
    font-size: 36px;
    &:hover {
      font-size: 50px;
    }
    &:active {
      opacity: 0;
    }
  }
`
  • animation: ${rotateAnimation} 1s linear infinite; ➡️애니메이션 스타일 적용
  • ${Emoji}{
        font-size: 36px;
        &:hover {
          font-size: 50px;
        }
        &:active {
          opacity: 0;
        }
      } ➡️Emoji 컴포넌트의 셀럭터 스타일

 

function App() {
  return (
    <Wrapper>
      <Box>
        <Emoji>😊</Emoji>
      </Box>
      <Emoji>❤️</Emoji>
    </Wrapper>
  );
}

export default App;
  • <Emoji>😊</Emoji> 해당 이모티콘은 Box 내부에 들어있는 컴포넌트이므로 애니메이션 속성이 적용되었다.
  • <Emoji>❤️</Emoji> 해당 이모티콘은 Box 외부의 컴포넌트이기 때문에 rotateAnimation 속성이 적용되지 않았다.

 

 

 

반응형

'Front-End > React(비공)' 카테고리의 다른 글

[React] TypeScript  (0) 2024.03.20
[React] styled components 3. theme darkmode 기초  (0) 2024.03.20
[React] styled components 1  (0) 2024.03.19
[React] 리액트 프로젝트 설치, 세팅  (0) 2024.03.19
React JS 기초 05. setState  (0) 2023.07.31