본문 바로가기
Front/React

[React] Context 를 사용하여 테마 변경 기능 만들기

by 오엥?은 2023. 4. 25.
반응형

 

  • src > chapter_14 > ThemeContent.jsx
import React from "react";

const ThemeContext = React.createContext();
ThemeContext.displayName = "ThemeContext";

export default ThemeContext;

 

  • src > chapter_14 > MainContent.jsx
import {useContext} from "react";
import ThemeContext from "./ThemeContext";

function MainContent(props) {
    const {theme, toggleTheme} = useContext(ThemeContext);

    return (
        <div
            style={{
                width: "100vw",
                height: "100vh",
                padding: "1.5rem",
                backgroundColor: theme == "light" ? "white" : "black",
                color: theme == "light" ? "black" : "white",
            }}
        >
            <p>안녕하세요, 테마 변경이 가능한 웹사이트 입니다.</p>
            <button onClick={toggleTheme}>테마 변경</button>
        </div>
    );
}

export default MainContent;

 

  • src > chapter_14 > DarkOrLight.jsx
import { useState, useCallback } from "react";
import ThemeContext from "./ThemeContext";
import MainContent from "./MainContent";

function DarkOrLight(props) {
    const [theme, setTheme] = useState("light");

    const toggleTheme = useCallback(() => {
        if (theme == "light") {
            setTheme("dark");
        } else if (theme == "dark") {
            setTheme("light");
        }
    }, [theme]);

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            <MainContent />
        </ThemeContext.Provider>
    );
}

export default DarkOrLight;

 

  • npm start

테마변경 누르면 테마가 막 바뀐다.

개발자 도구를 열어 Component -> MainContent 를 눌러보면 테마가 흰색일 때는 theme: "light",

테마가 검은색일 때는 theme: "dark" 로 변경되는 것을 확인할 수 있다.

반응형