skip to Main Content

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


  1. Chosen as BEST ANSWER

    As recommended by @Siamak, i managed to implement require.context() to solve the issue, so here is the final code

    function About() {
        
        const imgFolder = require.context('./img/', false)
        
        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'))
    
        //make the image change every 5secs
        useEffect(() => {
            //Implementing the setInterval method
            const interval = setInterval(() => {
                counter === 3 ? setCounter(0) : setCounter(counter + 1);
                setAboutImg( require(`${tempImg[counter]}`))
                console.log(`aboutImg = ${aboutImg}`)
            }, 5000); // every 5secs it changes
    
            //Clearing the interval
            return () => clearInterval(interval);
        }, [counter]);
    
            return (
               <img src={aboutImg}/>
            )
        
     }
        
     export default About;
    

  2. 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:

    import React, { useState, useEffect } from 'react';
    
    // Import all images
    import horsebackRiding from './img/Horseback-riding.jpg';
    import snowshoeing from './img/Snowshoeing.jpg';
    import yoga from './img/yoga3.3.jpg';
    import rope from './img/rope.jpg';
    
    function About() {
    const tempImg = [horsebackRiding, snowshoeing, yoga, rope];
    
    const [counter, setCounter] = useState(0);
    const [aboutImg, setAboutImg] = useState(tempImg[0]);
    
    useEffect(() => {
    const interval = setInterval(() => {
    setCounter(prevCounter => (prevCounter === tempImg.length - 1 ? 0 : 
    prevCounter + 1));
    setAboutImg(tempImg[counter]);
    }, 5000);
    
    return () => clearInterval(interval);
    }, [counter, tempImg]);
    
    return (
    <img src={aboutImg} alt="About" />
    );
    }
    
    export default About;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search