React Styled Components (2) Theme

우디·2021년 12월 24일
5

React

목록 보기
2/4
post-thumbnail

공식문서

1. Why Theme?

(1) 한번의 동작으로 사이트에서 색상 등을 바꿔줄 수 있다

3 번에서 자세히 다뤄보겠당

(2) 홈페이지에 다크모드를 구현한다면

Styled Components의 Theme과 State Management(Recoil, Redux 등)를 이용하여 구현할 수 있다
Recoil에 대한 글을 작성한 후, 직접 구현하는 글도 올릴 예정이다

2. theme 사용을 위한 사전준비

보통 index.js 파일에서 작성한다

(1) ThemeProvider를 import 해준다

import { ThemeProvider } from "styled-components";

(2) App 컴포넌트를 ThemeProvider로 감싸준다

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={}>
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

이 때 ThemeProvider에는 위와같이 theme prop이 필수이다
prop에는 사용할 이름과 색을 오브젝트 형식으로 넘겨준다

(3) theme prop에 넘길 오브젝트를 작성 후 원하는 theme을 theme prop 에 전달한다

const darkTheme = {
  textColor: "skyblue",
  bgColor: "#111",
};

const ligthTheme = {
  textColor: "#111",
  bgColor: "skyblue",
};

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

이 때 각 색을 담은 오브젝트에서 색의 이름은 동일하게 해주는게 좋다
왜 그런지 조금더 읽다보면 알 수 있다

위의 과정을 마쳤다면 theme을 사용할 준비는 끝났다고 볼 수 있다

3. 사이트에 적용 시키기

(1) 동작 원리

현재 나의 App 컴포넌트는 ThemeProvider로 감싸져 있기 때문에, App 컴포넌트에서 theme에 접근하는 것이 가능하다

(2) 사용 방법은?

사용 방법은 아주아주 간단하다

이전 글에서 styled component안에서 prop을 전달해서 사용했던 방식과 동일하게 사용할 수 있다

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

const Title = styled.h1`
  color: ${(props) => props.theme.textColor};
  font-size: 36px;
  font-weight: 600;
`;

function App() {
  return (
    <Components>
      <Title>Hello World!!</Title>
    </Components>
  );
}

이 때 props.theme.~~의 ~~는 색상의 이름을 정해둔 오브젝트에서의 이름과 같아야 한다

여기서 ThemeProvider의 theme prop 을

<ThemeProvider theme={darkTheme}>

에서

<ThemeProvider theme={ligthTheme}>

로 바꿔보자

위 처럼 단 한번의 간단한 작업으로 배경색과 글자색을 바꿀 수 있었다

단, darkTheme과 lightTheme에서 색상 이름을 같게 해줬기 때문에 가능한 것이다
위에서 말했 듯, style component안에서 theme prop안 오브젝트의 이름을 읽고 있기 때문이다


이렇게 간단하게 theme에 대해서 정리해 보았다

이 글에서는 background-color와 color 두 개만을 이용했기 때문에 굳이..?라는 생각이 들 수 있으나,
사이트의 규모가 커진다면 매우 유용하게 사용할 수 있다 (a태그일 때, hover일 때, active일 때의 색 등등)

State Management인 Recoil을 블로그에서 다룬 후에, 다크모드를 구현하는 것도 포스팅 할 계획이다

더 자세한 내용은 공식문서에서 확인할 수 있다

profile
계정 이전했습니다 https://velog.io/@rjw0907/posts

0개의 댓글