styled-components(with React) theme을 이용하는 방법

이지원·2022년 1월 22일
1

style-components

목록 보기
3/3

theme이란

theme은 공통으로 사용할 style을 지정하는 방식이다.하나의 object에 style을 정의 해두는것이다
예를들어 A와B라는 컴포넌트에서 공통적으로 사용하는 style이 있다면
A와B에 각각 style을 지정하는것보다 하나의 파일을만들고 그 파일에서 해당 style을 불러오면 될것이다.
이 포스팅에서는 아주 간단히 theme을 이용해 다크모드 화이트모드를 구현할 수 있는 방법을 설명하겠다.

ThemeProvider

styled-components에서는 theme을 설정하기 위해선 ThemeProvider라는 모듈을 사용해야한다.
ThemeProvider는 context api방식으로 작동한다.
(react에서는 context api를 지원하고 있는데,
context api 방식이란 하나의 컴포넌트안에서 전역으로 데이터를 공유하도록 나온 개념이다.)

사용방법

styled-components에서 theme을 사용하는 방법으로는 우선 import해준다.

import { ThemeProvider } from "styled-components";

위에서 설명한 context api 방식으로 동작하기떄문에 react의 기본설정에서
index.js 파일이 가장최상위로 존재하기 때문에
index.js 파일에 import한다.

index.js 파일

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider>
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

위와 같이 ThemeProvider 컴포넌트로 App 컴포넌트를 감싸주면 App 컴포넌트에서 ThemeProvider를 통한 prop을 받을 수 있다.

자 이제 초기 설정은 완료 되었다.
theme을 관리하는 파일을 생성해보자.

theme 파일 설정하기

theme.js 파일

export const darkTheme = {
    fontColor: "black",
    backgroundColor: "white"
}

export const whiteTheme = {
    fontColor: "white",
    backgroundColor: "black"
}

theme 설정을 완료 했으면
index.js파일에서 해당 theme.js파일에 있는 style파일을 사용해올 수 있다.
index.js 파일

import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from 'styled-components';
import App from './App';
import { darkTheme,whiteTheme } from './theme';


const isDark = false;

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={isDark ? darkTheme : whiteTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

theme을 사용하기!

isDark라는 변수는 다크모드인지 화이트모드인지 해당하는 변수가 변경되면 다크,화이트 모드로 변경해주기 위한 변수이다.
ThemeProvider 파일에서는 theme이라는 props를 넘겨주면 index.js 세팅은 끝이다.
자 이제는 context api 방식으로 App 컴포넌트에서 셋팅한 theme을 사용하면 끝이다.
App.js 파일

import styled from "styled-components";

const Wrapper = styled.div`
  display: flex;
  height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items: center;
  background-color: ${(props) => props.theme.backgroundColor};
`;
const Text = styled.h1`
  color: ${(props) => props.theme.fontColor};
`;
export default function App() {
  return (
    <Wrapper>
        <Text>hello world</Text>
    </Wrapper>
  );
}

Text와 Wrapper에서는 props를 바로 이용할 수 있다.
styled-components에서 props를 이용하는 방법은
링크
를 참고하면 될것이다.

profile
안녕하세요 피드백은 언제나환영입니다.

0개의 댓글