0

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.

Rounin
  • 27,134
  • 9
  • 83
  • 108
Nedu
  • 49
  • 9
  • 1
    Possible duplicate of [Setting a backgroundImage With React Inline Styles](https://stackoverflow.com/questions/39195687/setting-a-backgroundimage-with-react-inline-styles) – The Reason Jun 02 '18 at 16:25

2 Answers2

1

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>
    );
  }
}
Abhishek Shah
  • 436
  • 1
  • 3
  • 12
1

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)

Rounin
  • 27,134
  • 9
  • 83
  • 108