How to load random icons every time React loads
P粉237647645
P粉237647645 2023-09-09 14:48:46
0
1
758

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粉237647645
P粉237647645

reply all(1)
P粉722521204

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template