Reputation: 291
This is my tree folder
├── public
│ ├── favicon.ico
│ ├── image.jpeg
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
├── README.md
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
├── reportWebVitals.js
└── setupTests.js
This is my App.css
.App {
text-align: center;
background: url("/image.jpeg");
}
This is my App.js
import "./App.css";
function App() {
return (
<div className="App">
<h1>asdasdasd</h1>
</div>
);
}
export default App;
I'm triying to add background-image to App.js but react throws this message
Failed to compile.
./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/App.css)
Error: Can't resolve '/image.jpeg' in '/home/ivan/Documents/code/REactJs/portafolio/src'
I'm dev on ubuntu 20, node version is v12.19.0
BTW I created this app yesterday and I dosen't work, but I have an old app I created a month ago and It works fine.
Upvotes: 3
Views: 8889
Reputation: 526
I have faced issues with background image urls.
On the internet, I found 2 answers:
public
directory, use absolute path.src
directory, use relative path.I have observed that these answers did not work if the css file or style is in one or more level deeper from the src directory.
├── public
│ ├── favicon.ico
│ ├── image.jpeg
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
├── README.md
└── src
├── App.css
├── App.js
├── a
│ └── b
│ ├── c.js
│ └── c.css
├── App.test.js
├── index.css
├── index.js
├── images
│ └── sample.png
├── logo.svg
├── reportWebVitals.js
└── setupTests.js
The following would work, as .logo
is kept in src/index.css
:
.logo {
background-image: url(images/sample.png)
}
But, the following will not, as the same is kept in a/b/c.css
:
.logo {
background-image: url(images/sample.png)
}
Finally, I learnt that, using absolute path works in all the scenarios. That is, the following works in all levels.
.logo {
background-image: url(/images/sample.png)
}
The above also means that, using absolute path when the files are kept in public
is not valid.
The whole thing is here.
Further reference:
Upvotes: 0
Reputation: 341
I don't think your App.css
file can read images from your public
folder, due to React's import restrictions from outside the src
folder (The create-react-app imports restriction outside of src directory). Instead, add an inline style to App
import "./App.css";
function App() {
return (
<div className="App" style={{ backgroundImage: "url('/image.jpeg')" }}>
<h1>asdasdasd</h1>
</div>
);
}
export default App;
Upvotes: 4
Reputation: 1
You are looking for image.jpeg in the wrong directory.
Your image.jpeg is found in /public, so try looking for it in background: url("../public/image.jpeg");
instead of background: url("/image.jpeg");
Upvotes: -1