본문 바로가기

프론트엔드/ReactJS 마스터

[React] styled component(5) - Themes

theme을 사용해서 darkmode와 lightmode를 적용해보겠습니다. 

theme이란? 여러가지 색상들을 가지고 있는  object입니다.

 

- theme 실행 방법

1) ThemeProvider import 하기

2) 환경셋팅 -> index.js 

  • App을 ThmemProvider로 둘러싸기
  • theme object 생성하기 -> dark/lignt mode를 가지는 두개의 theme은 property가 똑같아야 합니다.
  • object를 ThemeProvider에 전달하기 -> ThemeProvider 안에 있는 모든 컴포넌트들은 이 object에 접근할 수 있게됩니다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ThemeProvider } from 'styled-components';

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>
);

 

3) theme 사용하기 -> app.js

props를 통해서 theme의 색상에 접근할 수 있습니다.

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 Title = styled.h1`
  color: ${(props) => props.theme.textColor};
`


function App() {
  return (
    <Wrapper >
      <Title>Title</Title>
    </Wrapper>
  )
}

export default App;

 

- darktheme 적용된 결과

 

지금은 darkmode와 lightmode를 설정할 때 ThemeProvider에 전달되는 theme={darkTheme} 혹은 theme={lightTheme}으로 변경해야하지만 다음에는 theme을 바꾸는 좋은 방법을 알아보겠습니다.

다음 포스팅부터는 typescript를 이용해서 theme 설정에 어떻게 도움 줄 수 있는지 배워보도록 하겠습니다!