next-themes
next-themes copied to clipboard
Fix flash on page load when using value mapping
When using value mapping there is a flash on page load (on both development and production). This is due to updateDOM
function returning empty (''
) and thus the attribute on <html>
is not set
Source of bug
The source of this bug is here: https://github.com/pacocoursey/next-themes/blob/8fc17e2a53aeb9e5918f8b9152795e56712ea862/src/index.tsx#L233
The condition if (resolvedName)
is not met when called here:
https://github.com/pacocoursey/next-themes/blob/8fc17e2a53aeb9e5918f8b9152795e56712ea862/src/index.tsx#L252
leaving the else
block useless
The produced scrept in ThemeScript
is as follows:
!(function () {
try {
var d = document.documentElement,
n = "data-theme",
s = "setAttribute";
var e = localStorage.getItem("theme");
if ("system" === e || (!e && true)) {
var t = "(prefers-color-scheme: dark)",
m = window.matchMedia(t);
if (m.media !== t || m.matches) {
d[s](n, "theme-dark");
} else {
d[s](n, "theme-light");
}
} else if (e) {
var x = { light: "theme-light", dark: "theme-dark" };
}
} catch (e) {}
})();
The last if block (else if (e)
) doesn't do anything on DOM
Fix
Adding || literal
to the condition in updateDOM
function to also call setAttribute
when value is passed literally
Before
After
The latest updates on your projects. Learn more about Vercel for Git ↗︎
Name | Status | Preview | Comments | Updated |
---|---|---|---|---|
next-themes-basic | ✅ Ready (Inspect) | Visit Preview | 💬 Add your feedback | Jan 13, 2023 at 9:54PM (UTC) |
next-themes-tailwind | ✅ Ready (Inspect) | Visit Preview | 💬 Add your feedback | Jan 13, 2023 at 9:54PM (UTC) |
Fixed in new script approach.