search

Home  >  Q&A  >  body text

How to load random icons every time React loads

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

In manifest.json, the icon is loaded as follows:

"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 select an icon from a set of icons?

P粉237647645P粉237647645518 days ago790

reply all(1)I'll reply

  • P粉722521204

    P粉7225212042023-09-10 11:35:32

    You can create an array of icons and use JavaScript's Math.random() function to randomly select an icon from the array. Reference 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 is installed. We use Math.random() to select a random icon from the icon array and update the icon by changing the href attribute of the label.

    reply
    0
  • Cancelreply