Theme Toggler with React and Context API

ยท

2 min read

Hey people welcome to the blog, i am yashvant and in this blog we gonna see how we can make theme toggler for react website, so let's get started.

Note:- I assumed that you have basic understanding of react.

Step-1

Create React Project with below command

npx create-react-app theme-toggler

After project has been made write

cd theme-toggler and write npm start to start the project

now open it in any editor like sublime,vscode or atom. I am using vs code.

now in the src folder create one folder and give it name store.

after creating a folder create one file and name it theme-context.js or anything.

In theme context js write below code

import { createContext, useEffect, useState } from "react";

const ThemeContext = createContext({
    theme: "light",
    toggle: () => {},
});

export const ThemeProvider = props => {
    const prevTheme = localStorage.getItem("theme");
    const [theme, setTheme] = useState(prevTheme);
    useEffect(() => {
        setTheme(theme);
    }, [theme]);

    const toggleTheme = () => {
        console.log("togglin");
        if (theme === "light") {
            setTheme("dark");
            localStorage.setItem("theme", theme);
        } else {
            setTheme("light");
            localStorage.setItem("theme", theme);
        }
    };
    const contextValue = {
        theme: theme,
        toggle: toggleTheme,
    };
    return (
        <ThemeContext.Provider value={contextValue}>
            {props.children}
        </ThemeContext.Provider>
    );
};

export default ThemeContext;

Go to index.js and write following code

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { ThemeProvider } from "./store/theme-context";
ReactDOM.render(
<React.StrictMode>
        <ThemeProvider>
                <App />
    </ThemeProvider>
    </React.StrictMode>,
    document.getElementById("root")
);

We have to import themeprovider to provide context in our app

go to the App.js

import "./App.css";
import ThemeContext from "./store/theme-context";
import { useContext } from "react";

function App() {
    const context = useContext(ThemeContext);
    localStorage.setItem("theme", context.theme);

    const toggleThemeHandler = () => {
        context.toggle();
    };
    return (
        <div className="App" data-theme={context.theme}>
               <button
                    className={`themetoggler ${toggleThemeHandler }`}
                    onClick={props.handleThemeToggle}
                >
                    <span role="img" aria-label="switch theme">
                        {props.theme === "dark" ? "๐ŸŒž" : "๐Ÿ”…"}
                    </span>
                </button>
        </div>
    );
}

export default App;

For theme styling create go to App.css file and write this code.

[data-theme="light"] { --text-color: black; --background-color: white; }

[data-theme="dark"] { --text-color: #fcfcfc; --background-color: #1d1c1c; }

.App { color: var(--text-color); background-color: var(--background-color); }

that's it, run it and you will see the theme toggler.

Thanks for the Reading, follow me for more easy tutorials

ย