Changing the CSS background in React when updates occur

Currently working on toggling the CSS background image within this React application. The images have been successfully imported and a variable called "image" is set to the imported image as the iteration increases/decreases with each click.

The issue I'm encountering is that the body background image does not update accordingly. My understanding was that the background image should refresh in the componentDidUpdate method, as the iterative buttons toggle setState which triggers a re-render.

import Background1 from "../images/bg/1.png";
import Background2 from "../images/bg/3.png";
import Background3 from "../images/bg/4.png";


class UserPreferences extends Component {
  constructor(props) {
    super(props);
    this.state = {
      backgroundNumber: 1
    };
  }

  buttonNumberCalcPlus = () => {
    this.setState({ backgroundNumber: ++this.state.backgroundNumber });
  };

  buttonNumberCalcMinus = () => {
    this.setState({ backgroundNumber: --this.state.backgroundNumber });
  };

  componentDidUpdate() {
    var currentBackground = "Background" + this.state.backgroundNumber;
    console.log(currentBackground);

    var image;

    if (this.state.backgroundNumber == 1) {
      image = Background1;
    } else if (this.state.backgroundNumber == 2) {
      image = Background2;
    } else {
      image = Background3;
    }

    var mainBg = {
      backgroundImage: "url( " + { image } + ")"
    };
    console.log(mainBg);
    document.body.style = { mainBg };
  }

  render() {
    return (
      <div>
        <MainMenuToolbar />
        <h2 className="texttimezonepref">Update background image.</h2>
        <button
          id="next"
          onClick={this.buttonNumberCalcPlus}
          className="addbutton"
        >
          NEXT
        </button>
        <button
          id="prev"
          onClick={this.buttonNumberCalcMinus}
          className="subtractbutton"
        >
          PREV
        </button>
      </div>
    );
  }
}

Questioning whether this approach to changing the background in componentDidUpdate is correct:

var mainBg = {
  backgroundImage: "url( " + { image } + ")"
};


document.body.style = { mainBg };

Answer №1

Using document.body.style in JSX is incorrect as it does not support the syntax

document.body.style = {{ backgroundImage: "url( " + { image } + ")"}}
.

The correct method would be to apply your style changes directly to the target, like this:

document.body.style.backgroundImage = url(image)

Answer №2

Instead of utilizing the style property to assign an object, it is recommended to use style.background. This adjustment is necessary because the style object is not a standard plain object but a CSSStyleDeclaration. For more information on this topic, you can refer to the documentation on MDN.

When it comes to accessing the document, while the current method may work, I suggest using react-helmet, which offers a more organized approach for updating the document.

Answer №3

Is it appropriate to modify the background in componentDidUpdate using this method?

Actually, no.

The entire document's structure isn't the only one that can utilize the full viewport, and adjusting the body of the document excessively is not advisable. Most often, your app resides within a <div id="#root">, so you should alter the style property of your root div rather than the body itself.

By manipulating document.body, you are essentially bypassing React by directly attempting to make changes to the DOM node. This should only be done through the use of refs.

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

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...

Develop a website using HTML and CSS for the front-end design, complemented by Java for the

I find myself at a standstill with a project I want to tackle, but unfortunately, my knowledge of modern web development, particularly full stack, is minimal. As a result, I am completely clueless on how to proceed. Here is what I am familiar with and what ...

Guide to displaying loading progress during server response delay in React with TypeScript

I need to find a way to update the loading state to false once the server responds. The challenge is that the response occurs in one component, while the progress bar is located in another. To illustrate the scenario: const Form: React.FC = () => { ...

Tips for resolving the warning message: "Utilize a callback function in the setState method to reference the

I'm having an issue with this code fragment as ESLint is giving me a warning: "Use callback in setState when referencing the previous state react/no-access-state-in-setstate". Can someone help me resolve this? const updatedSketch = await ImageManipula ...

Having issues with the link page in react-router-dom?

Currently, I am utilizing the react-router-dom library to manage routers. However, I have encountered an issue where linking to another page does not change the page, but instead adds the new page right after the previous one as shown in the image below. W ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...

The issue of DatePicker and LocalizationProvider not appearing persists on MUI core v4.12.3 when paired with MUI Lab v5.0.0-alpha.57

I'm currently working on integrating the DataPicker and LocalizationProvider with MUI v4.12.3. Below are the package JSON imports: "react": "17.0.2", "@material-ui/core": "4.12.3", "@material-ui/icons" ...

Using the `preventDefault` method within an `onclick` function nested inside another `onclick

I am currently working on an example in react.js <Card onClick="(e)=>{e.preventDefault(); goPage()}"> <Card.body> <Media> <img width={64} height={64} className="mr-3" ...

Having difficulty getting the sign operator to show up in a text field

Whenever the ADD div is clicked, "+" should be displayed on the textbox. The same goes for SUBTRACT, MULTIPLY, and DIVIDE. However, I am struggling to make the operators show on the textbox. Here is what I have managed to come up with so far. <!D ...

Incorporate child routes within a React component

I've been attempting to include <route> in a component within a routers component, but it doesn't seem to be working. Can anyone provide some assistance? My login page currently has a form and I'd like to switch that out with routes. ...

Reactjs is retrieving several items with just one click on individual items

I am having trouble getting only a single sub-category to display. Currently, when I click on a single category, all related sub-categories are showing up. For example, in the screenshot provided, under the Electronic category, there are two subcategories: ...

Fade-in effect on one DIV element impacting the values of other div

As a newcomer to jquery and JavaScript, I'm facing some challenges in getting the desired functionality. Currently, I am trying to animate three images simultaneously - one moving downward (iphone), another fading in (shadow), and the third one animat ...

Exploring the capabilities of useRef in executing a function on a dynamically created element within a React/Remix/Prisma environment

I've been trying to implement multiple useRef and useEffect instructions, but I'm facing difficulties in getting them to work together in this scenario. The code structure involves: Remix/React, fetching data from a database, displaying the data ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Unable to find the import "@mui/x-charts/PieChart" in the file "src/components/Pie/Pie.jsx". Could the file be missing or spelled incorrectly?

I utilized the PieChart component in my pie.jsx file pie.jsx import { PieChart } from '@mui/x-charts/PieChart'; const Pie = () => { return ( <div> <PieChart series={[ { data: [ ...

Changing the color of an open Bootstrap 4 accordion panel when the page loads

I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet. In certain scenarios, the first panel is open by default ...

Unable to retrieve session in NextJS/NextAuth AppRouter

Recently, I set up my NextJS application and followed the tutorial for NextAuth from various sources including videos. As of now, my application is nearly functional, but I'm facing difficulties with making the getServerSession function work. In my / ...

Scrolling with Jquery window.scrollTo results in the page becoming unresponsive

I'm currently revamping a website that features a header with 100% screen height, but I need it to shrink down to 0px when a user starts scrolling. The issue I'm facing is that once the header shrinks to 0px, the page content ends up slightly abo ...

capturing the value of a button during the onChange event

I'm currently trying to retrieve the button value within an onChange event. My goal is to then bind this value to state, but unfortunately, I am receiving an empty value. <button onChange={this.handleCategoryName} onClick={this.goToNextPage}> ...

`I am unable to insert an image into PrimeReact`

I am struggling to integrate images into the dashboard using primereact. Despite placing my photo folder in the public directory and entering the correct photo path, the image is not displaying on the page. I have attempted numerous methods but have been ...