Home > Back-end >  Dynamically changing favicon in react.js
Dynamically changing favicon in react.js

Time:06-05

So I am currently working on a website in react, and I am trying to change the favicon dynamically.

I had found a snippet of code which I tried to adapt in order to make it work but clearly I'm still missing something. My website does not break but there are no changes.

Here is my code:

    import Logo from './Images/logo.png';



    function App() {
    
      //need help
      useEffect((url) =>{
    
      let link = document.queryCommandValue("link[rel~={Logo}]");
      if(!link){
        link = document.createElement('link');
        link.rel = 'icon';
        document.getElementsByTagName('head')[0].appendChild(link);
      }
      link.href = url;
    
    },[]); 
  return (
    <div className="App">

CodePudding user response:

You can do it using React's useEffect hook and some JavaScript. Usually, you would define your useEffect in your page components, so when your page is rendered, the effect triggers which updates the favicon.

const Page1 = (props) => {
  // effect to update favicon
  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>Page1</div>
  );
}

Here's more on how to change favicon dynamically with just JavaScript

  • Related