randomly change the background color of a react app by a click

Viewed 3790

i tried to randomly change the background color of the entire page by a clicking a button but instead it was only changing the background of the div element. here is my code

  import React from "react";
  class Home extends React.Component {
      constructor(props) {
    super(props);
    this.state = {
        quotes: ["red", "yellow", "blue", "green", "purple", "pink"],
        colors: [],
    };
    this.nextColor = this.nextColor.bind(this);
}
// moves to display next quotes 
nextColor() {
    const random = this.state.quotes[Math.floor(Math.random() * this.state.quotes.length)]
    console.log("receiving ", random);
    this.setState({
        colors: random
    })
}
render() {
    return (
        <div style={{backgroundColor: this.state.colors}}>
            <h1>{this.state.colors}</h1>
            <button onClick={this.nextColor}>Next Color</button>
        </div>
    )
  }
  }

   ReactDOM.render(<Home />, document.getElementById("app")); 

i need the background color of the entire page to change when the nextColor button is clicked. your help would be appreciated

3 Answers

The body tag is not controlled by React. To modify the body tag hook on to componentDidMount life cycle and set the color using vanilla javascript

Here is a way https://jaketrent.com/post/update-body-class-react/

In a nut shell add the below logic

  componentDidMount() {
    document.body.style.backgroundColor = this.state.colors;
  }

Ramesh give the right answer, here is the demo:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colors: ["red", "yellow", "blue", "green", "purple", "pink"]
    };
  }

  changeBg() {
    const { colors } = this.state;
    const color = colors[Math.floor(Math.random() * colors.length)];
    document.body.style.backgroundColor = color;
  }

  render() {
    return (
      <div>
        <button onClick={() => this.changeBg()}>Change Color</button>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<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>
<div id="root"></div>

import React from "react";

function MyComponent({ name }) {
  // I found this formula
  // here: https://css-tricks.com/snippets/javascript/random-hex-color/
  let randomColor = Math.floor(Math.random() * 16777215).toString(16);

  // The trouble I had was about how to use
  // the variable randomColor in "style:{}" tag
  return (
    <div className="parent-container">
      <div
        className="child-container"
        style={{ backgroundColor: "#" + `${randomColor}` }}
      >
        <h4 className="name">{name}</h4>
      </div>
    </div>
  );
}

export default MyComponent;
Related