Theme Switcher


Web Development

Updated Jun 8th, 2021

It’s important to Have your dark and light theme colors mapped out before you start building your site.

CSS variables are great but if you define them with the wrong name when you make your theme switcher you’ll have to go back and change all the names anyway.

Another thing to consider with respect to colors is although it’s a dark theme you still want contrast within the dark theme and contrast within the light theme.

If you have “heavy contrast” within your default theme, I’m not even sure how much a theme switcher is even going to benefit you. You need to have “lightly contrasted” elements within each dark and light themes. What I mean by this is if you have a really dark header and then a white background and then all of a sudden you switch to dark and now the background is dark and the header is white what have you really accomplished?

More on naming conventions: First off, figure out your game plan before! There is a bit of a debate on –primary/–secondary versus –red/–blue and I preferred the first since you may change your color scheme entirely. After implementing my first dark theme switcher there seems to be a better third strategy that includes naming by element. This includes naming thing like –border-color, —–navbar-color, –heading-color, –text-color, –link-color, –link-color-hover etc. You almost need this in addition to –primary/–secondary for elements that do not change on theme switcher. The number’s of colors you need can escalate quickly. For one element you have a color and a background. With a theme switcher now you have four colors you need to manage. You have to watch carefully that you don’t mess up another style.

Actual Functionality

It’s all about [data-theme=”dark”] {} in your CSS which is just a custom attribute and is configured with document.documentElement.set attribute().

Very interesting that it’s a useState and useEffect and even local storage to have your theme preference persist on refresh.