Background Image not showing on build React

Viewed 2928

I have a component structured like this:

<div style={{ backgroundImage: `url(${require("src/assets/images/loginImage.png")})`, backgroundSize: 'cover' }}>

my folder structure is the following : Folder structure

Now, the image background shows up correctly when I run locally. But when I build and deploy online, the image doesn't show up.

The funny thing is that the icons do get loaded with no problems, and i refer to them in the same way

Does any of you have a clue on why this is happening?

Thanks

2 Answers

you can try this

Import loginImageFrom "src/assets/images/loginImage.png";

<div style={{ backgroundImage: `url(${loginImage})`,backgroundSize: 'cover' }}>

If you are using react, the pattern is to use import statements instead of require. Based on your Webpack config, you might not be able to use an inline require.

"Dynamic imports make it impossible for a static analyzer to determine whether imported code is ever actually called.

... The authors of the ES2015 Modules specification solved this issue in the import spec. They did this by disallowing the dynamic use of import. This is invalid javascript:"

The CreateReactApp docs also specify using import statements. Doc links are below

import loginImage from "src/asets/images/loginImg.png"

<div style={{ backgroundImage: `url(${loginImage})`, backgroundSize: 'cover' }}>

See React Import vs Require

As a Create React App Docs

Related