React Js show Random Image From array
React Js Show Random Image From Array -: In this ReactJS example, an image generator component is created to display a random image from an array. The component utilizes React's state and lifecycle methods to manage the image selection. Upon rendering, a random image is chosen from the predefined array and displayed. Each time the component re-renders, a different random image is shown, creating a dynamic image generator using React.




Thanks for your feedback!
Your contributions will help us to improve service.
How to display a random image from an array in Reactjs?
This React JS example displays a random image from an array of image URLs. The component uses React hooks, including useState and useEffect. Upon mounting, it sets a random image as the initial state and renders it. When the "Random Image" button is clicked, a new random image is displayed. The array contains several image URLs, and the getRandomImage function selects a random URL from the array and updates the state with it.
React Js Show Random Image From Array Example
<script type="text/babel" data-presets="env,react">
const { useState, useEffect } = React;
function App() {
const imageUrls = [
"https://www.sarkarinaukriexams.com/images/import/sne4446407201.png",
"https://www.sarkarinaukriexams.com/images/import/sne86811832.png",
"https://www.sarkarinaukriexams.com/images/import/sne10272423583.png",
"https://www.sarkarinaukriexams.com/images/import/sne1586776004.png",
"https://www.sarkarinaukriexams.com/images/import/sne20464172895.png",
// Add more image URLs as needed
];
const [randomImageUrl, setRandomImageUrl] = useState("");
const getRandomImage = () => {
const randomIndex = Math.floor(Math.random() * imageUrls.length);
setRandomImageUrl(imageUrls[randomIndex]);
};
useEffect(() => {
getRandomImage(); // Call this function to set a random image on component mount
}, []);
return (
<div className="container">
<h3>React Js Show Random Image</h3>
{randomImageUrl && <img src={randomImageUrl} alt="Random" />}
<button onClick={getRandomImage}>Random Image</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>