How do I change the favicon based on the system theme using Next 13?
Unanswered
Selkirk Rex posted this in #help-forum
Selkirk RexOP
This doesn't work:
Layout:
Favicon:
Layout:
<Head>
<Favicon />
</Head>Favicon:
'use client'
import { useTheme } from 'next-themes'
export function Favicon() {
const { theme } = useTheme()
const isDark = theme === 'dark'
return (
<link
rel="icon"
href={isDark ? '/favicon-inverted.ico' : '/favicon.ico'}
sizes="any"
/>
)
}3 Replies
Donskoy
Copy your favicon file (my one named favicon. ico ) to the public folder located in your project root directory (create one if it doesn't exist). The default favicon will be overwritten.
@Donskoy Copy your favicon file (my one named favicon. ico ) to the public folder located in your project root directory (create one if it doesn't exist). The default favicon will be overwritten.
Selkirk RexOP
Thanks, but I'm having a problem with changing it client side, the default one already shows up fine!
Selkirk RexOP
ended up using:
'use client'
import { useTheme } from 'next-themes'
import { useEffect } from 'react'
export function Favicon() {
const { resolvedTheme } = useTheme()
useEffect(() => {
const link: HTMLLinkElement =
document.querySelector("link[rel*='icon']") ||
document.createElement('link')
const favicon = resolvedTheme === 'dark' ? '/inverted.ico' : '/favicon.ico'
link.type = 'image/x-icon'
link.rel = 'icon'
link.href = favicon
document.head.appendChild(link)
}, [resolvedTheme])
return null
}