I have an image on my About page of a react app which i’d like the image to change to a new image every 5secs. I have set up my hooks and my aboutImg state is initially set to require(‘./img/rope.jpg’) which renders the image. But when I try to dynamically update this I get the following error for each path way I try to dynamically add:
Cannot find module './img/Horseback-riding.jpg'
at webpackEmptyContext (http://localhost:3000/static/js/bundle.js:64374:10)
at http://localhost:3000/static/js/bundle.js:2974:68
My code is:
function About() {
const tempImg =['./img/Horseback-riding.jpg','./img/Snowshoeing.jpg','./img/yoga3.3.jpg','./img/rope.jpg']
const [counter, setCounter] = useState(0);
const [aboutImg, setAboutImg] = useState(require('./img/rope.jpg'))
useEffect(() => {
//Implementing the setInterval method
const interval = setInterval(() => {
counter === 3 ? setCounter(0) : setCounter(counter + 1);
setAboutImg(require(tempImg[counter]))
// setCount(count + 1);
}, 5000); // every 5secs it changes
//Clearing the interval
return () => clearInterval(interval);
}, [counter]);
return (
<img src={aboutImg}/>
)
}
export default About;
I have consoled.logged aboutImg and can see it’s showing the correct string but when i add the variable into the require() it causes this error
Emma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.