Jorgio
Jorgio

Reputation: 111

Background Image not showing on build React

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

Upvotes: 4

Views: 5206

Answers (2)

ikmo
ikmo

Reputation: 298

you can try this

import loginImage from "src/assets/images/loginImage.png";

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

Upvotes: 4

CaliTab
CaliTab

Reputation: 156

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

Upvotes: 1

Related Questions