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

Time:11-21

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

CodePudding user response:

Try changing the className value of your form-container based on the theme.

jsx:

...
   <form className={theme === "light" ? "form-container light" : "form-container dark"}>
...

css:

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

.form-container.light {
  background-color: rgb(54, 118, 139);
}

.form-container.dark {
  background-color: black;
}

CodePudding user response:

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;
}
  • Related