[React] styled component (3) _ theme

404·2022년 7월 10일
0

React.js

목록 보기
3/9
post-thumbnail

디자인을 정형화하고 쉽게 변경하기 (feat. Dark mode)

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

const root = ReactDOM.createRoot(document.getElementById("root"));
const darkTheme = {
  textColor: "whitesmoke",
  backgroundColor: "#111",
};

const lightTheme = {
  textColor: "#111",
  backgroundColor: "#whitesmoke",
};
root.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

ThemeProvider"styled-components" 로 부터 import 하여 사용한다.

위 코드처럼 <App /> 컴포넌트를 ThemeProvider 안에 있게 하고 theme 속성을 설정해준다.

이렇게 하면 ThemeProvider 안의 컴포넌트들이 theme 속성을 받아 쓸 수 있게된다.

이전 포스팅에서 사용한 예제에 덮어보면 아래와 같다.

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

const Parent = styled.div`
  display: flex;
  height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items: center;
  background-color: ${(props) => props.theme.backgroundColor};
`;

const Rotation = keyframes`
0% {
  transform: rotate(odeg);
  border-radius: 0px
}
50%{
  border-radius: 150px;
}
100% {
  transform: rotate(360deg)
}`;

const Box = styled.div`
  background-color: ${(props) => props.bgColor};
  width: 300px;
  height: 300px;
  animation: ${Rotation} 1s linear infinite;
  display: flex;
  justify-content: center;
  align-items: center;
  h1 {
    color: white;
    &:hover {
      color: black;
    }
  }
`;

function App() {
  return (
    <div>
      <Parent>
        <Box bgColor="tomato">
          <h1>Loading...</h1>
        </Box>
      </Parent>
    </div>
  );
}

export default App;

코드가 예제가 길지만 봐야할 부분은 Parent 컴포넌트에 background-color 부분이다. 해당 코드에서 사용한것 처럼 theme 속성을 받아 사용할 수 있다.

장점

  1. 다크모드와 라이트모드 객체를 별도로 생성하여 버튼 클릭시 변경해주는 방식으로 사용이 가능하다.

  2. 디자인 색상을 객체화시켜 사용함으로써 디자인 통일성을 얻게되며 수정작업이 빠르고 간편해진다.

주의점

  1. 여러가지 theme 객체를 사용할 떄는 그 안의 속성 이름을 통일시켜줘야 추가작업 없이 빠르게 변경사항을 반영할 수 있다.
profile
T.T

0개의 댓글