How can you update the background image of a particular div using the 'onclick' feature in React.JS?

Thank you for helping me out here. I'm currently working with ReactJS and facing a challenge where I need to change the background of a div from a color to a specific image URL upon clicking a button in a modal. Despite my efforts, I keep encountering the following error:
TypeError: Cannot read property 'style' of null

While I am able to successfully log the image URL and div ID within the onclick function, I seem to be hitting a roadblock when it comes to styling the div itself. Any guidance or assistance on this matter would be greatly appreciated!

Below is the button triggering the action:

<button onClick={() => { this.changeUserBG(this.state.AlexPics[0], "one") }} className="btn btn-danger">Kaalia of the Vast</button>

And here's the function being invoked:

  changeUserBG = (imageUrl, userArea) => {
        let thisOne = document.getElementById(userArea);
        console.log(thisOne)
        thisOne.style.backgroundColor = 'red'
        // document.getElementById("one").style.backgroundImage = `require(url(${imageUrl}))`;

    } 

The target div that I'm attempting to modify looks like this:


<div className="col-6" id="one">

       <div className="">

         <p className="lifeArea">
          <button className="minusOne" onClick={() => { 
              this.subtractOne("playerOne") }}>-1</button>
             <span id="playerOne">40</span>
             <button className="plusOne" onClick={() => { 
             this.addOne("playerOne") }}>+1</button>
         </p>

{/* Theme Modal that has ASK sub modals */}
<p className="bgCheckButton">
<button type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModalScrollable">Theme</button>
</p>
</div>

If you're interested in discussing MTG (Magic: The Gathering), I'm all ears for that too!

Answer №1

When working with React, it's recommended to avoid using getElementById or any other method that directly manipulates the DOM. Instead, you can achieve what you need by following this approach:

<div style={{backgroundImage: this.state.image}}>...</div>

By setting the state like this:

this.setState({ image: 'some_value.png' });

The background image will automatically be updated. If you want to change the background of different divs based on their ID, you can use a map in your state as shown below:

clickHandler = (divId, color) => {
   this.setState(state => ({ backgroundColors: { [divId]: color, ...state.backgroundColors} }));
}

At first glance, the line of code above may seem complex if you're unfamiliar with the spread operator. However, its purpose is simple - it adds a new key to the map called backgroundColors stored in the state.

You can then utilize it like this:

<div id="foo" style={{ backgroundImage: this.state.backgroundColors["foo"]}}>...</div>

Answer №2

To access the reference of a div in React, you can utilize the ref API and then modify the style property of the div.

Example Code

Within Class Constructor



constructor() {
  this.userAreaRef = React.createRef();
}

changeUserBG = (imageUrl, userArea) => {
  let thisOne = this.userAreaRef;
  console.log(thisOne)
  thisOne.current.style.backgroundColor = 'red'
}

Render

 <div ref={this.userAreaRef} className="col-6" id="one">
            <div className="">
                <p className="lifeArea">
                    <button className="minusOne" onClick={()=> { 
this.subtractOne("playerOne") }}>-1</button>
                    <span id="playerOne">40</span>
                    <button className="plusOne" onClick={()=> { 
this.addOne("playerOne") }}>+1</button>
                </p>
                {/* Theme Modal that has ASK sub modals */}
                <p className="bgCheckButton">
                    <button type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModalScrollable">Theme</button>
                </p>
            </div>
        </div>

Within Functional Component

const someFunction = () => {
  const userAreaRef = useRef();

  changeUserBG = (imageUrl, userArea) => {
    let thisOne = userAreaRef;
    console.log(thisOne)
    thisOne.current.style.backgroundColor = 'red'
  }

  return (
    <div ref={this.userAreaRef} className="col-6" id="one">
            <div className="">
                <p className="lifeArea">
                    <button className="minusOne" onClick={()=> { 
this.subtractOne("playerOne") }}>-1</button>
                    <span id="playerOne">40</span>
                    <button className="plusOne" onClick={()=> { 
this.addOne("playerOne") }}>+1</button>
                </p>
                {/* Theme Modal that has ASK sub modals */}
                <p className="bgCheckButton">
                    <button type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModalScrollable">Theme</button>
                </p>
            </div>
        </div>
  );
}

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

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

What is the best way to define a:link style within a div class structure?

I am trying to include an anchor tag within my HTML... Inside the tag, I have the following CSS code: .foo { white-space:nowrap; text-shadow: 0 -1px 0 #000; color: #000; font-family: Helvetica Neue, Helvetica, arial; font-size: ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

Prevent outside clicks from closing the React Ant Design drawer by disabling the functionality

Does anyone know how to disable the outside click option in the ant design drawer component for my react project? Here is a link to a working example on StackBlitz Below is the code snippet: import React from 'react'; import ReactDOM from &apo ...

next.js encountered an issue with the product.map function not being recognized

I am trying to retrieve data from a REST API to display on the front end. I have used getStaticProps() for this purpose, but when I try to map the data from the props, it throws an error saying it is not a function. Upon inspection, I found that the data r ...

Maintaining the functionality of an AJAX web page even after extended periods of inactivity

When using my one-page web app, I sometimes leave the page open overnight and find that when I come back in the morning, things don't work as they should. It seems like Javascript is acting up - edit-in-place loads incorrect data, ajax calls fail to f ...

An issue has arisen where I encounter the error message: 'TypeError: callback is not a function', even though the function appears to be continuing to run successfully

Encountering an error message 'TypeError: callback is not a function' while attempting to execute a particular function. Here is the code snippet in question: const api = require('axios'); getData(printData); async function getData ...

Ensure you are using the appropriate .env file when constructing your next.js project

Below are the necessary files for CI/CD, dockerfile, next.config.js, and package.json. The pipeline runs smoothly without any errors and the project launches successfully. However, while on the development branch, it continues to use .env.production instea ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

Using Node.js to schedule and send notifications to a specific topic via FCM

In order to deliver topic notifications to Android devices using FCM, I have set up an Angular application and a Node.js server. The scheduling of these notifications is handled by the bull library. The process involves two methods of sending notification ...

Tips for ensuring a function in Angular is only executed after the final keystroke

I'm faced with the following input: <input type="text" placeholder="Search for new results" (input)="constructNewGrid($event)" (keydown.backslash)="constructNewGrid($event)"> and this function: construct ...

Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors. Looking to switch components using v-if and passing different properties. Here's a small example: Currently, when switching from 'blue' to 'red ...

What is the method to retrieve the color of a linearGradient in an SVG at a particular

I am working on a unique progress bar that uses a linear gradient and a small ellipse to indicate the completion percentage. The AngularJS binding updates the completion percentage and a function is called. My challenge is to change the color of the ellip ...

When switching from page 1 to page 2 in a React MUI Data table, the cell data does not update to reflect the API response

Imagine a scenario where there is a parent component containing a child component that acts as a MUI data table. This child component receives API response data from the parent component as props. Problem: The data in the table loads perfectly on initial ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

How can we eliminate identical elements from an array in JavaScript and increment the count of other objects?

I currently have 1 object retrieved from local storage, but it seems to contain some duplicates. What is the easiest way to remove these duplicates? The array object I am working with is called "mainchart". function check() { for (let i = 0; i < main ...

Serializing intricate objects using JavaScript

I'm curious if there are any options outside of npm for serializing complex JavaScript objects into a string, including functions and regex. I've found a few libraries that can do this, but they all seem to depend on npm. Are there any good seri ...