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!
document.getElementById(userArea);in react code is strongly discouraged, I'd recommend looking at a react tutorial if you're new to it. Assuming you know what you're doing though - the error implies that<span id="playerOne"></span>isn't available on the page when you click the -1 button. I'd suggest verifying that it exists with dev tools before clicking it. I'd be willing to bet that it's not the div you were expecting, but a 3/3 Elk instead.thisbinding? I know that the primary advantage to using An arrow()=> {...}overfunction()is that the arrow locks thethiscontext. (But I stick by "Never expect this to be what you think this is")