jnara jnara - 10 months ago 52
React JSX Question

TypeError when Dynamically Changing CSS in ReactJs Component

I am trying to change the background color of my ReactJs web app dynamically when pressing the up arrow on a keyboard. However, when running this code, I am receiving the following error message:

Uncaught TypeError: Cannot read property 'setAttribute' of null

The component that this piece of code is placed in has one parent which renders the entire app.

handleKeyDownEvent(event) {

if (event.keyCode == 38) {

/*if up key or swipe up*/
if (this.state.isInverted == false) {
document.getElementById("body").setAttribute("background-color", "#000000");
this.setState({ isInverted: true });
else {
document.getElementById("body").setAttribute("background-color", "#FFFFFF");
this.setState({ isInverted: false });

How would I fix this? Any suggestions on better methods to change the background color dynamically in React?



If you are just trying to change the background color of the body element you can just do document.body.style.backgroundColor = 'red'