JSFiddle - React, Tailwind, and code Playground
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: false
}
}
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
});
this.state.auto && setInterval(() => {
this.setState({
color: this.getNextColor(this.state.color)
});
}, 1000);
}
render() {
this.switchAuto = this.switchAuto.bind(this);
return (
<div className='App'>
<TrafficLight color={this.state.color} />
<input type="button" onClick={this.switchAuto} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('#root'));