Created
December 4, 2018 23:39
-
-
Save kkotelczuk/4f72b2032ace24ce4549dd7097b66caa to your computer and use it in GitHub Desktop.
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"; | |
class Timer extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
timer: 0, | |
secondsRemaining: "00", | |
minutesRemaining: "00", | |
hoursRemaning: "00" | |
}; | |
} | |
timerIntervalId = null; | |
setDisplayValue = value => (value < 10 ? `0${value}` : value); | |
tick() { | |
const { timer } = this.state; | |
if (timer - 1 <= 0) { | |
clearInterval(this.timerIntervalId); | |
this.setState({ | |
secondsRemaining: "00", | |
minutesRemaining: "00", | |
hoursRemaning: "00", | |
timer: 0 | |
}); | |
return; | |
} | |
var hours = parseInt(timer / 3600, 10); | |
var minutes = parseInt((timer - hours * 3600) / 60, 10); | |
var seconds = parseInt(timer % 60, 10); | |
this.setState({ | |
secondsRemaining: this.setDisplayValue(seconds), | |
minutesRemaining: this.setDisplayValue(minutes), | |
hoursRemaning: this.setDisplayValue(hours), | |
timer: timer - 1 | |
}); | |
} | |
componentDidMount() { | |
const { minutes, seconds, hours } = this.props; | |
const timer = minutes * 60 + hours * 3600 + seconds; | |
this.setState( | |
{ | |
timer, | |
minutesRemaining: this.setDisplayValue(minutes), | |
hoursRemaning: this.setDisplayValue(hours), | |
secondsRemaining: this.setDisplayValue(seconds) | |
}, | |
() => (this.timerIntervalId = setInterval(() => this.tick(), 1000)) | |
); | |
} | |
componentWillUnmount() { | |
clearInterval(this.timerIntervalId); | |
} | |
render() { | |
const { minutesRemaining, secondsRemaining, hoursRemaning } = this.state; | |
return ( | |
<div> | |
{hoursRemaning} : {minutesRemaining} : {secondsRemaining} | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Timer hours={1} minutes={12} seconds={23} />, | |
document.getElementById("root") | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment