-
-
Save codecademydev/c22bfd78facefdaaae5b815805c1160a to your computer and use it in GitHub Desktop.
Codecademy export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import {Button} from './Button.js' | |
class Random extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
color: [67, 200, 80] | |
}; | |
this.handleClick = this.handleClick.bind(this); | |
} | |
componentDidMount() { | |
this.applyColor(); | |
} | |
handleClick() { | |
this.setState({ | |
color: this.chooseColor() | |
}); | |
} | |
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') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment