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

Creating a default homepage across various HTML files using Google Apps Script and deploying it as a WebApp

Is there a way to set a default main page on multiple HTML and GS files in Google AppScript? I plan to publish it as a Web App. Have you attempted using the doGet function? ...

React hooks problem with toggle arrow functionality

Could anyone assist me with the following issue: I have a React Hooks component where I am trying to toggle an arrow when clicking on a span element. It currently works only once, and if clicked again, it does not work anymore. I am confused as to why th ...

Modify CSS using Javascript by targeting the class of ".modalDialog > div {}"

I am currently working on a project that involves creating a Modal Layer using CSS. I have successfully implemented the modal layer, but now I need to figure out how to change the width from the default 400px to something else when I open it with Javascrip ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

The functionality of bootstrap.styl malfunctions during the parsing process in stylus

I am attempting to incorporate stylus, a css preprocessor, with twitter bootstrap version 2.04. Upon downloading boostrap, I execute the command "stylus --css < bootstrap.css > bootstrap.styl" to generate a bootstrap.styl file. However, upon trying to p ...

Having trouble with CSS3 radio buttons not functioning properly on Firefox?

Does anyone know why my CSS3 pseudo elements are working fine in Chrome, but reverting back to default styling in Firefox for my radio button? Any suggestions? Check out this JSFIDDLE link for reference: JSFIDDLE Here is the HTML code snippet: <input ...

Error message: Experiencing an issue with over-renders in React when using onMouseEnter and onMouse

Here is my initial component where I handle routing. I added two navigation items with some styling, but encountered an error due to excessive re-rendering. The issue arose when adding a hover effect without using CSS. Here's the code snippet: import ...

Utilizing ScrollView Component in React Native

I have developed a simple app that displays a collection of images with titles, resembling a film gallery where all available films can be viewed. However, I encountered an issue when trying to implement the ScrollView element as it does not allow for scro ...

What sets classes prop apart from className prop in Material-UI when adding custom styles?

Can anyone explain the difference between the classes prop in Material-UI (mui) and the className attribute? It seems like they both serve the same purpose, but I want to clarify that I am not referring to the classes variable within the component which co ...

Maintain HOVER State in CSS Drop Down Menu upon Clicking

I have implemented a CSS Drop Down Menu on my website. In a specific section of the site, I am using the menu links to trigger AJAX-jQuery calls that dynamically change the content of a DIV without the need for page reloading. <script type="text/javasc ...

Changing the MaterialUI icon when it is clicked

Each item in a list has an "AddIcon". Upon clicking the icon, I want to replace it with a "BlockIcon" based on its unique "id". import React from 'react' import {List, ListItem} from '@material-ui/core' import AddCircleIcon from ' ...

What steps should be followed to incorporate a horizontal scrollbar within the table's header?

I'm currently using Vue and Vuetify to create a unique layout that looks like this: https://i.stack.imgur.com/QBs3J.png The layout consists of a card with three rows: The first row displays the number of items and includes a search bar. The second ...

Updating the state on change for an array of objects: A step-by-step guide

In my current scenario, I have a state variable defined as: const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>(); My goal is to update this state by using a TextField based on the name and value of each input ...

The BottomNavigation element in Material UI shifts from the bottom position when the screen is resized

Seeking advice for my React app where I am trying to implement a footer that remains at the bottom of the screen consistently. I have been adjusting the layout of components based on screen size using media queries, switching the display property from fle ...

Challenges surrounding asynchronous functionality in React hooks

I've been facing some issues with this code and have resorted to debugging it using console.log(). However, the results I'm getting are not making any sense. Can someone help me identify what's wrong with this code? I noticed that my console ...

Hidden overflow and identification in URL causes content to be invisible and suddenly appear at the top of the page

I'm encountering a strange issue with containers that have overflow:hidden and when the page URL includes an id. The content gets pushed up and becomes invisible. This problem arises when I apply padding and negative margin at the bottom to create equ ...

What is the best method to achieve a width of 100% for an element (textarea) that has unspecified borders and padding, while also including the borders and padding

Native borders for input controls in various browsers often look more visually appealing compared to those set with CSS. However, the thickness of these native borders and padding can vary across different browsers, making it difficult to predict beforehan ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Switching the theme color from drab grey to vibrant blue

How can I change the default placeholder color in md-input-container from grey to Material Blue? I have followed the instructions in the documentation and created my own theme, but none of the code snippets seems to work. What am I doing wrong? mainApp. ...

Discovering the enter key on the IonSearchBar device

My goal is to trigger the Search function when the enter key on the device is pressed, but I am facing issues. Although I can filter words using onIonChange Which event should be used to detect the enter key press on the device? The onIonInput event does ...