[Styled-Component] Theme

Jihyun-Jeon·2022년 2월 25일
0

HTML,CSS

목록 보기
32/34

🔶 ThemeProvider를 이용해 다크모드↔️라이트모드 바꾸기

ThemeProvider가 다른 컴포넌트를 모두 감싸어 theme을 prop으로 보내게 됨.
이 때 theme prop에 "darkTheme" 또는 "lightTheme"을 보내어 하위 컴포넌트에서 prop을 받아 사용하게 된다.
이렇게 하면 하위 컴포넌트인 Wrapper에서 일일히 색을 바꾸지 않아도 된다.


1. theme.js에서 공통된 테마를 선언함.

< theme.js >

export const darkMode = {
  textColor: "white",
  backgroundColor: "black",
};

export const lightMode = {
  textColor: "black",
  backgroundColor: "white",
};

2. ThemeProvider를 통해 theme를 prop으로 전해줌

< index.js >

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

import { ThemeProvider } from "styled-components";  // 1. ThemeProvider를 import함
import { darkMode, lightMode } from "./theme";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
// 2.<ThemeProvider> 를 젤 상단에 두어 모든 컴포넌트가 theme에 영향 받도록 하고, theme prop을 설정해줌
  <ThemeProvider theme={darkMode}>   // darkTheme 또는 lightTheme 로 테마 변경가능
    <App />
  </ThemeProvider> 

3. props로 받아와서 theme prop 사용해줌

< App.js >

import styled from "styled-components";

const Wrapper = styled.div`
  width: 100vw;
  height: 100vh;  
  background-color: ${(props) => props.theme.bgColor}; // 3.theme prop 사용
  color: ${(props) => props.theme.txtColor}; // 3.theme prop 사용
`;

// 4.이후 app컴포넌트 안에 있는 모든 컴포넌트에서, 이 theme이 적용되는 것임
function App() {
  return <Wrapper>
    // ...내용생략(다른 많은 styled components)
    </Wrapper>;
}

export default PracThemeApp;

0개의 댓글