Make a custom night mode toggle w/React & CSS Variables
David Y Soards
Posted on August 25, 2019
This post is the first in a short series where I will detail the things I learned while designing and developing a website to promote AIGA Louisville's annual Design Week. Please have a look and let me know what you think in the comments.
I tried a couple other methods to achieve this effect that involved using React's Context API before settling on simple CSS variables. The trouble I ran into using Context was that it simply triggered a re-render and switched the theme colors immediately without applying a transition animation.
I also believe that the best method is often the simplest method and using CSS variables is a win in that respect. The only issue is that (wah-waaah, get ready) they aren't supported in IE 🙄. Because this site is aimed at designers, the vast majority of whom are using a modern browser on their desktop (many of them a Mac where IE isn't an option at all) or using their smartphone to access the site, I reason that full IE support is not required.
Alright, now onto the fun stuff.
The CSS Variables
Step one is to set the CSS variables on the root in the global CSS file so they can be accessed anywhere in the DOM (or in this case the virtual DOM).
Because I'm attempting to "partially" support IE11 for this project, I'm using fallbacks by first setting the element directly to a hex code and then overriding that with the variable. The override will be ignored by any browser that doesn't support CSS variables.
With the variables set globally in the CSS, new values can be assigned as needed using JavaScript. I started by creating two color theme objects -- lightTheme & darkTheme -- inside my main layout.js component.
Up first, inside the component, there are 2 useState hooks. One to set the mode and one to toggle the switch.
Next, a useEffect hook loops over the values in the chosen mode object and assigns the correct colors to the corresponding CSS variables. The 2nd argument tells React to only re-render if currentMode changes.
A second useEffect checks localStorage upon page load for a 'mode' item set to 'dark'. If this item is found it toggles to dark mode. For this hook the 2nd argument is an empty array, which means the effect will be run only once on the initial load of the page (similar to how ComponentDidMount works in class components).
The toggleTheme function updates the checked status to the opposite of what it is currently set to and switches the mode from 'dark' to 'light' or 'light' to 'dark'. It also sets the 'mode' item inside localStorage to the new mode.
Because the ToggleSwitch component is located inside of the Header component, the toggleTheme and isChecked functions need to be passed into the Header and then into the ToggleSwitch.
A toggle is just a checkbox with some CSS magic applied to it. 🧙♂️
The jsx for the component consists of a div (Toggle), an input with type="checkbox", and a span (Slider). On the checkbox input, toggleTheme is assigned to onChange and isChecked is assigned to checked.
As you can see I'm using CSS-in-JS 🙀 via the @emotion/styled library. If you are familiar with styled-components, it works almost exactly the same but the package is slightly smaller and apparently more performant (I haven't actually tested it, so what do I know?). Emotion also gives you the option of using css props to style components, which can be useful in certain situations.
To use styled-components, you simple rename your HTML tags to whatever makes sense semantically, and then define which native HTML elements your new tags should use with the CSS for each element inside back-ticks. The API supports nesting similar to SCSS, and the styles are SCOPED TO THE COMPONENT!
Personally, I love how semantic and simple this makes my JSX markup. No more jamming 14 different classnames onto every element ala Bootstrap or writing disgusting classnames like "header__toggle-switch--dark-mode" ala BEM.
The official Design Week 2019 website for AIGA Lou
AIGA Lou Design Week 2019
Gatsby
Gatsby is an Static-Site-Generator for React and uses GraphQL to query data usually from Markdown files (JAMStack). It gives developers all the benefits of a dynamic web app and serves it up as super fast HTML, CSS, and vanilla JS.