Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const ReactDOM = require('react-dom')
const React = require('react')
const TimerButton = (props) => {
return (
<button type="button" onClick={()=>{
props.handler(props.time)
}}>Start {props.time}</button>
)
}
const TimerLabel = (props) => {
return <div>{props.timeLeft}</div>
}
class TimerWrapper extends React.Component {
constructor(props) {
super(props)
this.startTimer = this.startTimer.bind(this)
this.state = {timeLeft: 0, intervalRef: null}
}
startTimer(timePeriod) {
clearInterval(this.state.intervalRef)
let intervalRef = setInterval(()=>{
if (this.state.timeLeft == 0 ) return clearInterval(this.state.intervalRef)
this.setState({timeLeft: --this.state.timeLeft})
}, 1000)
this.setState({intervalRef: intervalRef, timeLeft: timePeriod})
}
render() {
return (
<div>
<TimerButton time="5" handler={this.startTimer}/>
<TimerButton time="10" handler={this.startTimer}/>
<TimerButton time="15" handler={this.startTimer}/>
<TimerLabel timeLeft={this.state.timeLeft}/>
</div>
)
}
}
ReactDOM.render(
<TimerWrapper/>,
document.getElementById('timer')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.