Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to background-image css in React.Js?

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.

like image 231
Ivandez Avatar asked Jun 05 '26 09:06

Ivandez


1 Answers

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;
like image 154
husseinfawazbc Avatar answered Jun 07 '26 23:06

husseinfawazbc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!