0

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

0

1 Answer 1

0

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.