Issue with Displaying Background Image

When trying to set my background image on CDM using document.body.style={mainBg}, I am not getting the expected result. Additionally, the console statement below it is printing out an empty string. Can anyone assist me in identifying what mistake I might be making?

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)
 }
}

UPDATE: My goal is to set the background image for the body element.

Answer №1

If your React.js application has the <body> element outside of it, you can use vanilla javascript instead of React.js to style the body.

A modern (2018) approach is to utilize the new CSS Typed-Object Model (CSSOM). This allows you to iterate through the properties and values in the mainBg object and apply them using the attributeStyleMap property for the document.body element.

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] + ';');
}

For more information on the CSS Typed-Object Model (CSSOM), check out this article

Answer №2

You might want to consider this approach

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserve the previous and current state within a React application

Within my code, there is a state called newuser that undergoes changes based on the inputs entered into the input fields. This change occurs once all input fields are filled and the submit button is clicked. The goal I have in mind is to store the current ...

Printing 'Dynamic page' twice in the NextJs console

I recently encountered a strange issue while working on a dynamic page in NextJs. I inserted Console.log('Dynamic page') in the code, but instead of logging once, it was logged twice. I even tried moving the log function into useEffect with an em ...

Enhancing the appearance of your website by incorporating external stylesheets and utilizing multiple class names through

Is it possible to use external CSS frameworks like Bootstrap, Semantic UI, or Foundation and still generate base64 class names? This could be achieved if there was a way to apply multiple class names. Currently, you can only assign one class name like thi ...

In an Electron-React-Typescript-Webpack application, it is important to note that the target is not a DOM

Rendering seems to be working fine for the mainWindow. webpack.config.js : var renderer_config = { mode: isEnvProduction ? 'production' : 'development', entry: { app: './src/app/index.tsx', //app_A: './src/a ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

Using CSS nth-child to create a two-column checkers layout

I have formulated a form on my website that divides into two columns by using floats. I am interested in creating a "checkered" effect for these columns. Can anyone guide me on how to utilize nth-child to achieve this design layout? For reference, please c ...

Swap the content of one div with another div using client-side code only

Currently, I am in the process of developing my personal website. To enhance user experience, I have implemented a vertical navigation bar on the left side of the page. My goal is to replace the content of a specific div with content from other HTML files ...

Is optgroup malfunctioning in IE 10?

My main question is: does optgroup not function properly in IE? The Plnkr code works fine in Chrome but encounters issues in IE 10. I'm trying to find a solution that will work across both browsers. Is this a known problem? In Chrome, I can expand/co ...

Rendering sibling components on Multiple Select Material UI in React

Here is my current challenge: I am trying to implement a multiple select feature with checkboxes in React using Material UI. The desired outcome should resemble the image linked below: https://i.stack.imgur.com/TJl8L.png I have structured my data in an a ...

Parent div overflowing due to vertical flex container

In my current project, I am attempting to design a layout with a fixed header and footer along with a dynamic content area that utilizes the remaining vertical space. The content-wrapper contains a lot of data, which may require a scrollbar to navigate. H ...

I am experiencing issues with a few of my design choices not functioning correctly

I am facing issues with some of my styles. I have put in a lot of effort, but there seems to be a problem with my menu. The last part of my CSS is not functioning correctly. When hovering over the menu content, I want it to turn black and... #site_menu { ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

Align elements vertically in flexbox container using Bootstrap 3 on Internet Explorer 10 and 11

Encountering a problem in IE10+11 when trying to vertically center two Bootstrap columns within a row using flexbox. The dynamic content in the columns requires the row to have a minimum height of 65px. However, if the content expands and spans multiple l ...

A versatile function that displays a loading icon on top of a specified div

Is it possible to pass an identifier for a particular div element to a function, where the function will display a loading image that covers the entire div, and then pass the same identifier to another function to hide the loading image? I am looking to cr ...

Reactjs Screen is failing to refresh properly, consistently lagging by one loop when making updates

After updating a record that is displayed on the screen, I noticed that the changes were not reflected in the MySql database. Despite attempts to refresh the array and filter the results, the screen remained stagnant. Only after manually refreshing the bro ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

Utilizing a React component within another component

Just getting started with React and curious about calling one component inside another. I have a RecipeCard.js file in my components folder: import React, { Component } from 'react'; import { Ingredients } from './Ingredients'; export ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

The font color in Bootstrap is set to be lighter than the background color

Bootstrap has made great improvements in displaying navbar item colours that blend well with the background colour of the navbar. Can we apply a similar technique to body text as well? For example, if the container background is purple, can we have the t ...

Troubleshooting: React Material UI's Textfield maxLength feature experiencing issues on Android devices

Utilizing React Material UI, I am attempting to enforce a maximum length for a TextField component. I attempted to establish the max length in inputProps as shown below: <TextField id="name" label="Name" inputProps={{ ma ...