Home > OS >  coding a toggle mode using state object
coding a toggle mode using state object

Time:11-21

I have a problem to write code: I have a state

const [theme, setTheme] = useState({ mode: "LIGHT" });

and I want to made a toggle function that change mode to 'DARK' and change DARK to 'LIGHT' by double click. how can I write it?

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

const DARK = "DARK";

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState({ mode: "LIGHT" });

  const toggleThemeMode = () => {
    setTheme();
    console.log(theme);
  };

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

const useTheme = () => useContext(ThemeContext);

export { ThemeProvider, useTheme, DARK };

CodePudding user response:

A sample e.g. with onDoubleClick event , but if you mean just on single click change event name to onClick

const {useState} = React;

const App = () => {
    const [theme, setTheme] = useState("Dark");
  
    const handleClick = () =>{
      setTheme(prev=> prev === "Dark" ? "Light" : "Dark")
    }
    return (
        <div className={`theme ${theme}`}>
           <h2> Double click to change the theme - current theme: {theme} </h2>
           <br />
           <br />
           <button className={`btn ${theme}`} onDoubleClick={handleClick}>Change Theme</button>
           <br />
           <br />
           <p>Some test data </p>
        </div>
    );
};


ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App/>
);
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.Dark{
  background: black;
  color: white;
}

.Light{
  background: white;
  color: black;
}

.theme{
  height: 100vh;
}

.btn{
 border: 2px solid pink;
 background: gray;
 border-radius: 5px;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

CodePudding user response:

You can just use the following code:

const [theme, setTheme] = useState("LIGHT");

...

setTheme(theme === DARK ? "LIGHT" : DARK);

Nevertheless I suggest you to at least provide also a const for "LIGHT" value or even better: an enum. If you want to stick with two values (light and dark), you can also define the state as a boolean.

  • Related