Search code examples
reactjsformstogglemode

How can I Change Form Colour When I switch from Dark to Light mode in React


Hello guys I got the following code in my app.js:

function App() {
  const [theme, setTheme] = useState('light');
  const toggleTheme = () => {
    if (theme === 'light') {
      setTheme('dark');
    } else {
      setTheme('light');
    }
  };
  useEffect(() => {
    document.body.className = theme;
  }, [theme]);
  return (
    <div className={`App ${theme}`}>
       <button onClick={toggleTheme}>Toggle Theme</button>

And the Following Css in my Form:

.form-container {
  width: 600px;
  height: 750px;
  background-color: rgb(54, 118, 139);
  border-radius: 8px;
  box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
}

So How can I change the background-color of my Form When Dark is toggled and When Light is toggled? Im using react coding


Solution

  • I'd suggest you use css variables for this. Assuming that you're setting the class names light and dark on the body itself. they should be applied automatically according to your theme on the form.

    .light {
      --form-bg: #4d4d4d;
    }
    .dark {
      --form-bg: #e1e1e1;
    }
    
    .form-container {
      width: 600px;
      height: 750px;
      background-color: var(--form-bg);
      border-radius: 8px;
      box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);
      display: flex;
      flex-direction: column;
    }