Dynamically change background images in React from local folder

Viewed 303

I've been trying to load background images dynamically on my React app, but it only works when I link to my Google drive. I want to do this locally, and I've pasted the images on the immediate directory. But it still won't load on my app. I have 21 images from 0-20 all png format in src folder

var bgp = Math.floor(Math.random() * 20);
this.setState({
  chrome: color,
  photo: bgp,
  quote: randomQuote.quote,
  author: randomQuote.name
})
render() {
    var bodyP = {
      backgroundImage: `url(${onUse}.png)`,
      transition: 'all linear 2.5s',
      height: '100vh',
      width: '100vw',
    }
    return ( <div id = "wrapper" onLoad = {this.getQuote} style = {bodyP} >
      </div>
    )
2 Answers

if it worked fine with goggle drive before then I'm pretty sure this is a problem with how you've written your directory path. try creating an and write your path leading to one of these pictures if the image didn't render, then keep trying to find the right way to write your path or take a look at some documentation until u see the image render, after that, u can use the right directory path in your code. hope this works for u.

I've figured it out. I moved the photo folder to the public folder and then used the (process.env.PUBLIC_URL) file path description to the public path as explained by https://create-react-app.dev/docs/using-the-public-folder/ and navigated to the photo folder. So my code looks like:

 getPhoto() {
    var bgp = Math.floor(Math.random() * 20);
   
   this.setState({
        photo: bgp,
    })
    
  }
  
var onUse = process.env.PUBLIC_URL + "/Quote-photos/"+ this.state.photo + '.png';

 var bodyP = {backgroundImage: `url(${onUse})`,
              transition: 'all linear 2.5s',
              height: '100vh',
              width: '100vw'}
  

Related