PythonCoder1981
PythonCoder1981

Reputation: 463

React CSS inline vs CSS external styling

I am have been seeing that some things do not work the same in react CSS inline styling vs CSS external sheet styling. I was having an issue with adding a background image to my react app. I could not get it to compile via the normal CSS way. It seemed that it could not resolve.

I ended up using an inline style approach that worked. I am not sure if this is the most efficient way to add background images.

What is the best way to add background images to react, inline or external.

Working code:

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;

File Structure in React Images in public folder

None working Code via external CSS

App.css

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

I have tried with the leading forward slash and removing the quotes. I get the same error.

Error in React

Upvotes: 0

Views: 716

Answers (1)

MB_
MB_

Reputation: 1747

Put your images folder in the 'public' directory as mentioned in the comments and to reach these images, uses:

process.env.PUBLIC_URL

examples :

<div style={{ background: `url(${process.env.PUBLIC_URL)/images/bg-pattern-top.svg` }}>
</div>



<img src={process.env.PUBLIC_URL + /images/bg-pattern-top.svg} alt="" />

Upvotes: 1

Related Questions