Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing favicon in react.js

Tags:

reactjs

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">
like image 424
Alexa Pettitt Avatar asked Feb 05 '26 14:02

Alexa Pettitt


1 Answers

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

like image 72
Haseeb Anwar Avatar answered Feb 12 '26 05:02

Haseeb Anwar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!