1

I have a project built in React and Django. I am also using Webpack to load the changes. I want to display images from the local drive.

The file from which I want to display the photos is in:

myProject/brandplug/static/app/photoGrid/SampleDisplay.jsx

The photos are located in:

myProject/brandplug/static/location_photos/

The index.jsx file is in:

myProject/brandplug/static/app/index.jsx

The html file within which React is rendered is in:

myProject/accounts/templates/index.html

So from SampleDisplay.jsx I tried importing the images like this:

const itemStyle = {
  backgroundImage: `{require("../location_photos/" + ${photoName})}`
};

And then:

<div style={itemStyle}>
</div>

Instead of "../location_photos/" I also tried using "../../location_photos/" and "../../brandplug/static/location_photos/".

However, the images are still not loaded.

How can I load them?

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
bsky
  • 19,326
  • 49
  • 155
  • 270

1 Answers1

0

You're just setting the backgroundImage to be a string, that happens to be the same sytax as require.

You could require the image and use that:

const itemStyle = {
    backgroundImage: {require(`../location_photos/${photoName}`)}
};

but I've never tried this. You may find THIS SO question useful.

I would suggest that you don't try to use webpack to load the image, but instead ask Django to serve it.

const itemStyle = {
    backgroundImage: `url("/static/location_photos/${photoName}")}`
};

which assumes you have set up your static files to be hosted at /static/

Also, you were slightly mis-using backtick string templates, i.e., you don't need the +:

`{require("../location_photos/${photoName}")}`
Community
  • 1
  • 1
Neil Twist
  • 1,099
  • 9
  • 12