Https://www.codecademy.com/paths/web-development/tracks/front-end-applications-with-react/modules/react-101-components-interacting-u/projects/random-color

https://www.codecademy.com/paths/web-development/tracks/front-end-applications-with-react/modules/react-101-components-interacting-u/projects/random-color

I’d appreciate some help with this code. I haven’t any idea where I have gone wrong!

Random.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from './Button';

class Random extends React.Component {
  constructor(props) {
    super(props);
    this.state = {color: [20, 185, 180]};
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    this.setState({color: this.chooseColor()});
  }
  
  componentDidMount() {
    this.applyColor();
  }

  componentDidUpdate(prevProps, prevState) {
    this.applyColor();
  }

  formatColor(ary) {
    return 'rgb(' + ary.join(', ') + ')';
  }

  isLight() {
    const rgb = this.state.color;
    return rgb.reduce((a,b) => a+b) < 127 * 3;
  }

  applyColor() {
    const color = this.formatColor(this.state.color);
    document.body.style.background = color;
  }

  chooseColor() {
    const random = [];
    for (let i = 0; i < 3; i++) {
      random.push(Math.floor(Math.random()*256));
    }
    return random;
  }

  render() {
    return (
      <div>
        <h1 className={this.isLight() ? 'white' : 'black'}>
					Your color is {this.formatColor(this.state.color)}
        </h1>
        <Button
          light={this.isLight()}
          onClick={this.handleClick()} 
        />
      </div>
    );
  }
}

ReactDOM.render(
  <Random />, 
  document.getElementById('app')
);

Button.js

import React from 'react';

export class Button extends React.Component {
	render() {
		return (
			<Button 
				className={ this.props.light ? 'light-button' : 'dark-button' } onClick={this.props.onClick}>
				Refresh
			</Button>
		);
	}
}

Can you give some more information about what error message you’re getting or what is not working?

Hi rhoffen,
Thanks for getting back to me.
Well there was no error message - just a blank screen.
Anyhow, I redid the project and managed to succeed but I still would like to know where I went wrong.
However, I can do a compare contrast on a text editor. I’m sure I’ll get to bottom of it.
Thanks again

I’m glad you got it to work. I’m learning React myself now, so it’s hard for me to spot problems quickly, but I could probably have gotten it eventually. I find those lifecycle functions particularly confusing, especially because so many of them are being deprecated now, so the React devtools just yells at you for using them.

1 Like