Reputation: 724
I am fairly new to ReactJS, and I am trying to incorporate an image onto a webpage I am working on. My goal is to have an image randomly selected and displayed. I am not receiving any syntax errors, but no images are appearing on my webpage. Is this not the correct way to display an image using ReactJS? Any guidance would be greatly appreciated!
import React, { useState, useEffect } from 'react';
import image2019_0201 from '../images/2019_0201.jpeg';
import image2019_0202 from '../images/2019_0202.jpeg';
import image2019_0203 from '../images/2019_0203.jpeg';
const images = [
image2019_0201,
image2019_0202,
image2019_0203,
];
export default function RandomWelcomePicture() {
const [currentImageIndex, setCurrentImageIndex] = useState(Math.floor(Math.random() * images.length))
const changeImage = () => {
const randomNumber = currentImageIndex;
setCurrentImageIndex(randomNumber);
}
useEffect(() => changeImage(), [])
return (
<image
src={images[currentImageIndex]}
/>
)
}
I am randomly selecting one of three images to appear on the page.
Upvotes: 0
Views: 480
Reputation: 1
import React, { useEffect, useState } from "react";
export default function App() {
const Img = [
"https://media.istockphoto.com/photos/doctor-in-a-home-visit-to-a-senior-man-picture-id1289183630?b=1&k=20&m=1289183630&s=170667a&w=0&h=FMmzSvzUCtDAoqKn4idZNAfolbjsJFMigUI1IsnLhdc=",
"https://media.istockphoto.com/photos/close-up-of-small-blue-gray-mobile-home-with-a-front-and-side-porch-picture-id1297687835?b=1&k=20&m=1297687835&s=170667a&w=0&h=Kj4yvWxQxYo_fc9801IJZrHCAXa06LNsiRLjovVfoQQ=",
"https://media.istockphoto.com/photos/an-asian-chinese-female-barista-making-coffee-with-coffee-machine-at-picture-id1281786410?b=1&k=20&m=1281786410&s=170667a&w=0&h=KRip-2qWjKkAMx9tNc97yWcBRTNMExmU2bgPiNm6wZQ="
];
const [currentImageIndex, setCurrentImageIndex] = useState();
const imageChandHandler = () => {
setCurrentImageIndex(Math.floor(Math.random() * Img.length));
};
useEffect(() => imageChandHandler(), []);
return (
<div>
<img src={Img[currentImageIndex]} alt="Image" />
<button onClick={imageChandHandler} style={{ display: "block" }}>
Genereate Image
</button>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upvotes: 0
Reputation: 1568
There is no JSX tag called image
exists.
Replace image
with img
<img
src={images[currentImageIndex]}
/>
Upvotes: 1