1

I'm trying to require an image from a location inside the SRC folder in React (not from public unfortunately) and the specific name of that image will be granted from props.

The issue is that I need the image to be set as the background image of a <div />. The image doesn't show up.

I tried that:

<div
      style={{
        backgroundImage: `url('${require(`../../assets/images/home/${banner?.srcString}`)}')`,
        backgroundSize: "cover"
      }}
    />

Is there any way to solve this without using <img /> and without moving all images to /public?

Commando
  • 358
  • 3
  • 16

1 Answers1

1

No, you can not require images dynamically from src directory, and it's not just limited to React, it's about all JavaScript frameworks that use Webpack internally. Also, this is exactly one of the use cases of public directory, as it's been mentioned in the documentation: When to Use the public Folder

You can also check the following links for more discussions around this question:

Load local images in React.js

How to give Image src dynamically in react js?

React, load images local from json

fsefidabi
  • 153
  • 1
  • 12