skip to Main Content

Is there a way to randomly load a new favicon every time the page is reloaded in React? I want to have a list of icons and have one randomly chosen every time the page loads.

In the manifest.json, the favicon loading looks like this:

"icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],

Is there any reasonable way to randomly pick an icon from a set of icons?

2

Answers


  1. Regarding this

    Is there any reasonable way to randomly pick an icon from a set of icons?

    Just use Math.random to get random index and pick an item from your icons array

    const randomIndex = Math.floor(Math.random() * icons.length);
    const randomIcon = icons[randomIndex]
    
    Login or Signup to reply.
  2. You can create an array of icons and use JavaScript’s Math.random() function to randomly select an icon from the array. Refer here:

    import React, { useEffect } from 'react';
    
    const icons = [
      'favicon1.ico',
      'favicon2.ico',
      'favicon3.ico',
      // add more icons here
    ];
    
    function App() {
      useEffect(() => {
        const randomIcon = icons[Math.floor(Math.random() * icons.length)];
        const link = document.querySelector("link[rel~='icon']");
        link.href = randomIcon;
      }, []);
    
      return (
        <div>
          {/* your app content */}
        </div>
      );
    }
    
    export default App;
    

    In the above example, the useEffect hook is to run some code when the component mounts. We’re selecting a random icon from the icons array using Math.random() and updating the favicon by changing the href attribute of the tag.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search