React Styled Components 심화

Adam·2024년 1월 31일
0

react

목록 보기
2/7

Styled Components에서 애니메이션

keyframes라는 것을 사용해서 Styled Components에서 애니메이션을 구현할 수 있다.
이를 위해 keyframes를 불러오자

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

그 후 비슷한 방식으로 애니메이션을 생성해 준다.

const rotationAnimation = keyframes`
  from{
    transform: rotate(0deg);
  }
  to{
    transform: rotate(360deg);
  }
`;

그 후 해당 애니메이션을 적용할 스타일에 해당 내용을 넣어준다.

const AnimationBox = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  animation: ${rotationAnimation} 1s linear infinite;
`;

해당 AnimationBox를 렌더링해주면 애니메이션이 정상적으로 적용된것을 볼 수 있다.

function App() {
  return <Father>
    <Btn>Log in</Btn>
    <Btn as="a" href="/">Log in</Btn>
    <Box bgColor="teal">
      <Text>Hello</Text>
    </Box>
    <Circle bgColor="tomato"></Circle>
    <Input></Input>
    <Input></Input>
    <Input></Input>
    <Input></Input>
    <AnimationBox></AnimationBox>
  </Father>;
}

Styled Components 객체 안에서 다른 객체 접근

아래와 같이 AnimationBox라는 Styled Components 객체안에 span이 있다고 하자.
이때 span은 Styled Componenets 객체가 아니다.
하지만 Styled Components에서는 해당 span에 접근을하여 수정을 할 수 있다.

const AnimationBox = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  animation: ${rotationAnimation} 1s linear infinite;
  display: flex;
  align-items: center;
  justify-content: center;
  span{
    font-size: 20px;
    &:hover{
      font-size: 40px;
    }
  };
`;

위와 같이 객체 안에 접근할 span 객체를 명시해주고 동일하게 스타일링을 해주면 된다.
Span에 추가적으로 hover(마우스를 올렸을때) 크기를 다르게 하려면 '&'로 추가적인 스타일링을하겠다는 것을 표기하고 스타일링하면 된다.

Theme

네이버나 레딧 같은 웹사이트를 보면 다크/화이트 모드를 지원하는 것을 쉽게 볼 수 있다.
물론 이를 css에 일일히 하드 코딩할 수 도 있겠지만, Styled Components의 Theme을 사용해서 쉽게 도입할 수 있다.

Theme을 사용하기 위해선 index.js에서 아래와 같이 ThemeProvider을 import 해주고 App을 ThemeProvider로 감싸줘야한다.

import React from 'react';
import ReactDOM from 'react-dom/client';
import {ThemeProvider} from "styled-components";
import App from './App';

const darkTheme = {
    textColor:"whitesmoke",
    backgroundColor:"#111",
}

const lightTheme = {
    textColor:"#111",
    backgroundColor:"whitesmoke",
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <ThemeProvider theme={darkTheme}>
            <App/>
        </ThemeProvider>
    </React.StrictMode>
);

이러면 App.js에서 theme provider을 사용할 수 있다.
예를 들어 App.js에서 만들었던 Styled Components 였던 Btn에서 theme의 backgroundColor을 사용하려면 다음과 같이 변경해주면 된다.

const Btn = styled.button`
  color: white;
  background-color: ${props => props.theme.backgroundColor};
  border: 0;
  border-radius: 15px;
`;
profile
Keep going하는 개발자

0개의 댓글

관련 채용 정보