Server Side Rendering Compatible CSS Theming
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
Earlier today I saw some discussion around how to implement light/dark mode theming for a server side rendered (SSR) React application, in this case it was using Waku, however this pattern is compatible with almost any modern React framework, e.g. Next.js, React Router, etc!
I quickly worked up a scrappy demo thats over here, but I figured I could expand on it a bit and outline what it does and how it works in more details. If you're just looking for the snippets of code - I recommend jumping to that demo where you can easily copy them!
Background Context:
Traditionally, handling light mode and dark mode theme differences usually meant writing a decent number of @media (prefers-color-scheme: dark) {} media conditions across your CSS. However as Tailwind has increased in popularity - it's becoming increasingly rare to hand write the CSS and instead increasingly more web applications are being authored using utility classes.
Tailwind and similar systems usually offer a nice developer experience for customizing styles based on the preferred color scheme (the dark: modifier in tailwind for example), however this only solves for half of the problem, the remaining issue is how do you determine when to apply the dark or light classname (or data attribute) to the wrapping element (usually on the html or body elements)?