Nedu
Nedu

Reputation: 59

Background Image not being displayed

I am setting my background image on CDM but document.body.style={mainBg} does not set the background image as I expected and the console statement below it prints out an empty string. Can anyone help me figure out what I am doing wrong?

const mainBg = {
 backgroundImage: 'url("../img/background.jpg")',
 backgroundPosition: 'center',
 backgroundRepeat: 'no-repeat',
 backgroundAttachment: 'fixed',
 backgroundSize: 'cover',
};


class Home extends Component {
 componentDidMount() {
    console.log(mainBg);
    document.body.style = {mainBg};
    console.log(document.body.style.backgroundImage)
 }
}

EDIT: I am looking to set the background image for the body.

Upvotes: 0

Views: 165

Answers (2)

Rounin
Rounin

Reputation: 29511

If the <body> element sits outside the React.js app, (which is usually the case), then, rather than using React.js to set the body styles, you can use vanilla javascript.

An up-to-date (2018) way to do this would be to use the new CSS Typed-Object Model (CSSOM) which will allow you to loop through mainBg and add each property and value to the attributeStyleMap property for the element document.body.

Working Example:

const mainBg = {
  width: '100%',
  height: '100vh',
  'background-image': `url("../img/background.jpg")`,
  'background-position': 'center',
  'background-repeat': 'no-repeat',
  'background-attachment': 'fixed',
  'background-size': 'cover',
  };


for (const declaration in mainBg) {
    
    document.body.attributeStyleMap.set(declaration, mainBg[declaration]);
    console.log('<body> has the declaration: ' + declaration + ': ' + mainBg[declaration] + ';');
}


Further Reading about the CSS Typed-Object Model (CSSOM)

Upvotes: 1

Abhishek Shah
Abhishek Shah

Reputation: 460

You should try like this

import Background from '../images/background_image.png';

var bckImg = {
  width: "100%",
  height: "400px",
  backgroundImage: `url(${Background})`
};

class Section extends Component {
  render() {
    return (
      <section style={ bckImg }>
      </section>
    );
  }
}

Upvotes: 1

Related Questions