TrafficLight
by Van Hai Le
HTML
<div id='root'></div>
CSS
.traffic-light {
display: flex;
flex-direction: column;
margin: auto;
width: 50px;
}
.traffic-light-bulb {
border-radius: 50%;
height: 50px;
width: 50px;
margin-bottom: 16px;
opacity: .3;
}
.traffic-light-bulb--on {
opacity: 1;
}
.red-bulb {
background-color: red;
}
.orange-bulb {
background-color: orange;
}
.green-bulb {
background-color: green;
}
React
const RED = 0;
const ORANGE = 1;
const GREEN = 2;
const NOCOLOR = 3;
class TrafficLight extends React.Component {
render() {
let {color} = this.props;
return (
<div className='traffic-light'>
<div
className={
color === RED ?
'traffic-light-bulb red-bulb traffic-light-bulb--on' :
'traffic-light-bulb red-bulb'}>
</div>
<div
className={
color === ORANGE ?
'traffic-light-bulb orange-bulb traffic-light-bulb--on' :
'traffic-light-bulb orange-bulb'}>
</div>
<div
className={
color === GREEN ?
'traffic-light-bulb green-bulb traffic-light-bulb--on' :
'traffic-light-bulb green-bulb'}>
</div>
</div>
)
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
color: NOCOLOR,
auto: true,
interval: 1
}
this.switchAuto = this.switchAuto.bind(this);
this.submitSecond = this.submitSecond.bind(this);
}
getNextColor(color) {
switch(color) {
case NOCOLOR:
return RED;
break;
case RED:
return ORANGE;
break;
case ORANGE:
return GREEN;
break;
case GREEN:
return RED;
break;
}
}
switchAuto() {
this.setState({
auto: !this.state.auto,
/* color: NOCOLOR */
});
}
submitSecond(e) {
let value = Number(e.target.value);
if (e.keyCode === 13) {
this.setState({
interval: value
});
}
}
render() {
clearInterval(this.timeId);
if (this.state.auto) {
this.timeId = setInterval(() => {
this.setState({
color: this.getNextColor(this.state.color)
});
}, this.state.interval * 1000);
}
return (
<div className='App'>
<TrafficLight color={this.state.color} />
<input type="button" onClick={this.switchAuto} value='Auto On/ Off' />
<p>
<label>
Time interval (Second)
{' '}
<input type='text' onKeyDown={this.submitSecond}/>
</label>
</p>
</div>
);
}
}
ReactDOM.render(<App />,...