Pleinair
Pleinair

Reputation: 449

Using React to change background color of a body element on click?

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?

Upvotes: 1

Views: 8613

Answers (2)

Daryl Wright
Daryl Wright

Reputation: 81

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>

Upvotes: 0

SquallQL
SquallQL

Reputation: 98

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

Upvotes: 6

Related Questions