Daniel S.
Daniel S.

Reputation: 123

Background Image won't show in React component

I'm creating a simple React app (using create react app as a starting point) in which the App.js returns the following:

  return (
    <div className="App">
      <NavBar />
      <Main />
    </div>
  );
}

export default App;

I'm attempting to add an image to Main with the following:

  return (
    <div className="bg">      
      <LogInSignUpModal />
    </div>
  );
}

export default Main;

In the file Main.css I have the following:

    /* The image used */
    background-image:  url("../../images/WorkoutRack.jpg");

    /* Full height */
    height: 100%;
    width: 100%;

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }

Unfortunately the image won't appear in the main component (the main component is supposed to take up the entire page below the NavBar. I've tried many different solutions found in other StackOverflow responses but none have worked. What am I missing here?

Upvotes: 2

Views: 1968

Answers (3)

Some Dev
Some Dev

Reputation: 410

Images included in css files are going to taken from the public folder, not the src one.

So make your url relative to where the files are stored within the public folder, including the css in the public file too should make it even easier.

If someone has doubts about this, I'll gladly reply to you in the comments.

Upvotes: 0

Nandha Frost
Nandha Frost

Reputation: 122

Hi we can load the image in couple ways in react components itself

import react from 'react'
import imageName from './location/of/image'

class App extends react.Component{
render(){
return(
<img src={imageName} alt="imagename"/>
}
}

2nd way is to using require All code are similar but instead of importing, require it

import react from 'react'
Const imageName = require ('./location/of/image')

class App extends react.Component{
render(){
return(
<img src={imageName} alt="imagename"/>
}
}

Upvotes: 1

Fatemeh Qasemkhani
Fatemeh Qasemkhani

Reputation: 2042

First check this answer: React won't load local images If that was not fault, check your parent style or use px for with and height.

Upvotes: 0

Related Questions