Jack Franklin
Jack Franklin

Reputation: 105

How to change background image of specific div with 'onclick' function in React.JS

Thanks for helping my needy butt. I am working with ReactJS and trying to get a div to change it's background from a color to a specific image url on click of a button in a modal. I have tried many things and keep getting this error:
TypeError: Cannot read property 'style' of null

I successfully console.log the image URL and div ID within the onclick function, but the div styling is getting nowhere...All help is appreciated!

Here is my button

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

here is the function I call

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

    } 

Here is the div area I am trying to manipulate:


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

wanna talk mtg? down for that too!

Upvotes: 1

Views: 3960

Answers (2)

Scalpweb
Scalpweb

Reputation: 1971

In react, you should not use getElementById or any method changing the dom. You could have something like this:

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

So whenever you do:

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

the background image will be updated automatically.

In your case, if you need to change different div background based on div ID, you could store a map in your state, something like this:

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

The line of code above might be hard to understand at first if you are not used to the spread operator, but what it does is actually simple: it adds a new key to map backgroundColors stored in the state.

And you would use it as such:

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

Upvotes: 2

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

You can use React ref api to get the refrence of the div and then you can change the style property of the div.

Sample Code

In 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>

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

Upvotes: 0

Related Questions