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;
The reason i was trying to use require is because i have 90+ images that i want to cycle through
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
2
Answers
As recommended by @Siamak, i managed to implement require.context() to solve the issue, so here is the final code
Webpack needs to know all possible modules at compile time, and dynamically requiring modules with variables can cause issues.
To solve this, you can take a different approach to dynamically load images. Let me know if the following works for you: