Best Practice for Switching Favicon Based on Theme in Next.js w. App Router #64869
-
Hey, I'm working on implementing dynamic favicons in a Next.js application that change based on the user's selected theme (light or dark mode). Currently, we are utilizing Has anyone successfully implemented this with the Thank you in advance for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I managed to get something working that may prove useful. It's not a clean solution at all but seems to work, keep in mind to add "use client" and nest it within the ThemeProvider. The getColor util I use to grab the color part of my theme which is made up of font + color. const Favicons = () => {
const { theme } = useTheme();
const color = getColor(theme);
useEffect(() => {
let link: HTMLLinkElement | null = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement("link");
link.rel = "icon";
document.head.appendChild(link);
}
link.href = `${env.NEXT_PUBLIC_URL}/favicon${color !== "light" ? `-${color}` : ""}.ico`;
}, [color]);
return <></>;
}; |
Beta Was this translation helpful? Give feedback.
-
In root
I solved it like this, hope it helps. |
Beta Was this translation helpful? Give feedback.
In root
layout.tsx
I solved it like this, hope it helps.