1

I am trying to change the background color of html body to red with a button click, but i only know how to do it with an element that is already inside body, not the body itself.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bgColor: ""
    };
  }

  boxClick = e => {
    this.setState({
      bgColor: "red"
    });
  };

  render() {
    return (
      <div className="App">
        <article className="experimentsHolder">
          <div
            className="boxClickCss"
            style={{ backgroundColor: this.state.bgColor }}
            onClick={this.boxClick}
          >
            Click Me!
          </div>
        </article>
      </div>
    );
  }
}

As you can see, i added style={{backgroundColor: this.state.bgColor}} to div, but i can't add it inside body since it's not in this file. Any help?

3
  • 3
    document.body.style.backgroundColor = 'red'; Commented Mar 7, 2019 at 19:02
  • Use a document selector like document.querySelector('body') document.getElementById('#body_id'), etc. Commented Mar 7, 2019 at 19:05
  • 2
    While most answers will probably tell you to change the backgroundColor, it's a poor choice because you're mixing presentation with logic. That is when the color changes, and another programmer wants to change it, there is not easy answer. Instead you should create a css class that does what you need and add/remove that class from the body html element. Commented Mar 7, 2019 at 19:39

2 Answers 2

6

It is usually a good practice to manipulate the DOM inside lifecycle methods See doc here. If this is important to you, you could use componentDidUpdate lifecycle method on your App.js component and from there use standard dom manipulation to find the body and update its background color. You can also check in the method to ensure that the previous state and current state changed before acting on it. It could look something like this:

class App extends Component {

constructor(props) {
 super(props);
 this.state = {
 bgColor: ""
 }
}

componentDidUpdate(prevProps, prevState){
  const { bgcolor } = this.state;

  if(prevProps.bgColor !== bgColor){
      const bodyElt = document.querySelector("body");
      bodyElt.style.backgroundColor = bgcolor;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an example of manipulating the body within a React component, adapted from Frederic Caplette's answer recommending to do so in lifecycle methods. However, I do agree with Erik Philips's comment above that this kind of manipulation is better done via adding/removing CSS classes. Using CSS classes decouples details of the styles from the component logic and enables extensibility without affecting that logic.

const docBody = document.querySelector('body');

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {bgColored: false};
    this.colorBackground = this.colorBackground.bind(this);
    this.clearBackground = this.clearBackground.bind(this);
  }
  
  colorBackground() {
    this.setState({bgColored: true});
  }
  
  clearBackground() {
    this.setState({bgColored: false});
  }
  
  componentDidUpdate(prevProps, prevState) {
    const { bgColored } = this.state;
    const className = 'redBg';

    if(prevState.bgColored !== bgColored){
      bgColored ?
        docBody.classList.add(className) :
        docBody.classList.remove(className);
    }
  }
  
  render() {
    return (
      <div>
        <a href="#" onClick={() => this.colorBackground()}>Turn Red</a>
        {' | '}
        <a href="#" onClick={() => this.clearBackground()}>Reset</a>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
.redBg {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<body>
<div id="root"></div>
</body>

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.