Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created December 2, 2020 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecademydev/c22bfd78facefdaaae5b815805c1160a to your computer and use it in GitHub Desktop.
Save codecademydev/c22bfd78facefdaaae5b815805c1160a to your computer and use it in GitHub Desktop.
Codecademy export
import React from 'react';
export class Button extends React.Component {
render() {
return (
<button onCilck={this.props.onClick}
className={ this.props.light ? 'light-button' : 'dark-button' }>
Refresh
</button>
);
}
}
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