useFavicon
React hook to change the page favicon.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useFavicon
sh
npx @novajslabs/cli add useFavicon
sh
pnpm dlx @novajslabs/cli add useFavicon
Or copy and paste the code into your project:
ts
import {useState} from 'react';
export const useFavicon = () => {
const [faviconUrl, setFaviconUrl] = useState(
(document.querySelector(`link[rel~="icon"]`) as HTMLLinkElement)?.href
);
const changeFavicon = (newFavicon: string) => {
let link = document.querySelector(`link[rel~="icon"]`) as HTMLLinkElement;
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = newFavicon;
setFaviconUrl(newFavicon);
};
return {faviconUrl, changeFavicon};
};
js
import {useState} from 'react';
export const useFavicon = () => {
const [faviconUrl, setFaviconUrl] = useState(
document.querySelector(`link[rel~="icon"]`)?.href
);
const changeFavicon = (newFavicon) => {
let link = document.querySelector(`link[rel~="icon"]`);
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = newFavicon;
setFaviconUrl(newFavicon);
};
return {faviconUrl, changeFavicon};
};
Requirements
React 16.8 or higher
Return values
faviconUrl
Type: string
The current URL of the page's favicon.
changeFavicon
Type: (newFavicon: string) => void
Set the page favicon.