PythonCoder1981
PythonCoder1981

Reputation: 463

React js Background Image

I am currently working on a simple react image that will have profile pictures of different user. I have run into an issue when I try to set the background image. I will have two background images but I am unable to place any. The images are in my public/images/ but nothing is showing up in the webpage.

I am adding the image in body{} in the CSS file "App.css".

App.css

body {
  margin: 0;
  font-family: var(--fontFamily);
  font-size: var(--fontSize);
  background-image: "url(/images/bg-pattern-top.svg)";
  background-size: contain;
  background-position: top;
}

App.js

import './App.css';
import PorfileCard from './PorfileCard';

function App() {
  return (
    <div>
    <PorfileCard/>
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

File Structure

Chrome Development Tool

Chrome React Tool

Upvotes: 0

Views: 3774

Answers (2)

Fabian Joseph
Fabian Joseph

Reputation: 48

It's definitely too late to help you but i was also facing the same problem and google bought me here finally fixed it you just have to add a dot "." in front the path like you're importing a module in a .js file In your case the fix is:

background-image: url("./../public/images/bg-pattern-top.svg");

:) Hope this helps someone

Upvotes: 0

PythonCoder1981
PythonCoder1981

Reputation: 463

The only way I was able to resolve this was via using inline styling on the main div in app.js.

import './App.css';
import PorfileCard from './PorfileCard';

function App() {
  const mystyle = {
    backgroundImage: "url(/images/bg-pattern-top.svg)",
    backgroundSize: "cover",
    backgroundRepeat: "no-repeat"
    
  }
  return (
    <div style={ mystyle }>
     <PorfileCard/>
    </div>
  );
}

export default App;

Upvotes: 3

Related Questions