how to display single image randomly? I have created an array of objects where the images are been added now I need to display those images randomly but one at once and it will change in the next reload.
const index= () => {
let gifGallery=[
{
src:'./Images/1.gif',
value:1
},
{
src:'./Images/2.gif',
value:2
},
{
src:'./Images/3.gif',
value:3
},
{
src:'./Images/4.gif',
value:4
},
]
return (
<>
<h1>Gif Gallery</h1>
<div>
{
what should be the logic here?????
}
</div>
</>
)
}
use this code
function getRandomImage(arr) {
const length = arr.length;
const randomIndex = Math.floor(length * Math.random())
return arr[randomIndex]
}
you can use random function to get the random index from your array
gifGallery[Math.random() * gifGallery.length].src
You can get a random value from an array of objects and use it in your return method.
let gifGallery=[
{
src:'./Images/1.gif',
value:1
},
{
src:'./Images/2.gif',
value:2
},
{
src:'./Images/3.gif',
value:3
},
{
src:'./Images/4.gif',
value:4
},
]
var randomObject = gifGallery[Math.floor(Math.random() * gifGallery.length)];
return (
<>
<h1>Gif Gallery</h1>
<div>
<image src={randomObject.src} alt={randomObject.value} />
</div>
</>
)