reactjstypescripttitlefavicon

Changing website favicon depending on the url


I have a client who would like our web application branded according to its url. They'd like to change the favicon of the page to be the logo of the private label and same with the title, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?

I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?

PS: we run our web app with React.js, TS, etc.

I have tried on the index.html page of our web application but this doesn't apply to a specific url


Solution

  • That is possible using different methods. One could be using UseEffect on pages where you need the other favicon, here is how you can do it:

    const somePage = (props) => {
     //now this useEffect does the job for you
      useEffect(() => {
        let link = document.querySelector("link[rel~='icon']");
        if (!link) {
          link = document.createElement('link');
          link.rel = 'icon';
          document.getElementsByTagName('head')[0].appendChild(link);
        }
        link.href = 'https://stackoverflow.com/favicon.ico';
      }, []);
    
      return (
        <div>somePage</div>
      );
    }
    

    Check this question as well if it is not all clear to you. As for the title you can do the same, or you can make the custom hook for it:

    export function usePageTitle(title: string) {
      const documentDefined = typeof document !== 'undefined';
      const originalTitle = useRef(documentDefined ? document.title : null);
    
     useEffect(() => {
        if (!documentDefined) return;
    
        if (document.title !== title) document.title = title;
    
        return () => {
          //@ts-ignore
          document.title = originalTitle.current;
        };
      }, []);
    }
    

    This is not hard to do and it is not heavy on the user's machine because it is just a simple HTML DOM Document Object manipulation. And you can make hooks for both of these things, or you can use it as simple useEffect in every component where you need it as a first example for favicon ico.