0

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) {
        event.preventDefault();

        /*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?

Thanks!

1
  • Can you show your markup? Doesn't seem like an element with id body exists. Commented Sep 11, 2016 at 4:36

2 Answers 2

1

background-color is not a html attribute, is a css property, you can change style attribute and then set background-color as a value for style attribute, for example:

document.getElementById("body").setAttribute("style", "background-color:#000000");

This line will be add a style attribute to the body tag:

<body style="background-color: #00000">
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.