We built color swapping functionality to allow users to flip between light and dark themes on an e-commerce page. The theme is set by default to the user's preferred setting, but the user can toggle back and forth using the theme swapping toggle.
Here's a link to the project repo.
Using CSS and React Hooks, this functionality is fairly straightforward to set up.
- First, ensure all your default light theme colors are set up in CSS as variables.
:root {
--color: #525252;
--background-color: #ffffff;
--translucent-background-color: rgba(255, 255, 255, 0.6);
--primary-accent-color: #525252;
--secondary-background-color: #f0f0f0;
--error: #ff0000;
--highlighted: yellow;
--link-color: #6d84b4;
--title-color: #ffffff;
--title-background: #4c4c4c;
--slider-color: #ffffff;
}
- Create a dark theme version of your colors, and insert underneath your light theme in your CSS file. Here, you are listening for a CSS attribute
theme
. If thetheme
is set todark
, you will override the default color settings.
[theme='dark'] {
--color: #ededed;
--background-color: rgb(37, 37, 37);
--translucent-background-color: rgba(80, 80, 80, 0.6);
--primary-accent-color: #949494;
--secondary-background-color: rgba(65, 65, 65, 0.7);
--error: #ff0000;
--highlighted: #8a6a30;
--link-color: #6fa5a5;
--title-color: #ffffff;
--title-background: #27544e;
}
- Set up a React
useState
hook in your App component. This hook initializes thedark
state variable for your App component to maintain.
const [dark, setDark] = useState(false);
- Set up a React
useEffect
hook that initalizes the color scheme based on the user's browser preferences. If a user's preference isdark
, we will both set thedark
state variable to true, and set the CSStheme
attribute todark
.
useEffect(() => {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.setAttribute("theme", "dark");
setDark(true)
}
}, []);
- Set up the toggle button within your App component, where clicking the element group
#theme-toggle
will flip the theme between light and dark.
<div id="theme-toggle" onClick={() => setDark(!dark)}>
<span className="toggle-icon">☀️</span>
<span className="toggle-icon">
<i className={`fa fa-toggle-on ${dark ? "" : "fa-flip-horizontal"} fa-2x`}></i>
</span>
<span className="toggle-icon">🌙</span>
</div>
- Finally, set up a second React
useEffect
that listens for thedark
state change and updates the CSS variable accordingly.
useEffect(() => {
if (dark) {
document.documentElement.setAttribute("theme", "dark");
} else {
document.documentElement.setAttribute("theme", "light");
}
}, [dark])
- Voila! Now you have your own impressive theme changing website!