Skip to content

Instantly share code, notes, and snippets.

@manjunatha-d
Last active June 30, 2018 18:42
Show Gist options
  • Save manjunatha-d/cff772667a5d032ee19ceecd00e6393c to your computer and use it in GitHub Desktop.
Save manjunatha-d/cff772667a5d032ee19ceecd00e6393c to your computer and use it in GitHub Desktop.
React Countdown Timer
import React, { Component } from 'react';
function getTimeComponents(milliseconds = 0) {
const seconds = Math.floor((milliseconds / 1000) % 60);
const minutes = Math.floor((milliseconds / 1000 / 60) % 60);
const hours = Math.floor((milliseconds / (1000 * 60 * 60)) % 24);
const days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
return {
days: prefixWithZero(days),
hours: prefixWithZero(hours),
minutes: prefixWithZero(minutes),
seconds: prefixWithZero(seconds)
};
}
function prefixWithZero(value = 0) {
return value < 10 ? '0' + value : value;
}
class CountDownTimer extends Component {
constructor(props) {
super(props);
this.state = { timeLeft: 0, timerId: null };
}
componentDidMount() {
this.setTimer();
}
componentWillUnmount() {
clearInterval(this.state.timerId);
}
setTimer() {
const endOfTimer = new Date(this.props.endsAt).getTime();
let timerId = setInterval(() => {
let currentTime = Date.now();
if (endOfTimer > currentTime) {
this.setState(() => ({ timeLeft: endOfTimer - currentTime }));
} else {
this.setState(() => ({ timeLeft: 0 }));
clearInterval(this.state.timerId);
this.props.onTimerEnd();
}
}, 1000);
this.setState(() => ({ timerId }));
}
render() {
const { timeLeft } = this.state;
const timer = getTimeComponents(timeLeft);
const { SEPARATOR = ':' } = this.props;
return (
<div className="countdown-timer">
<div className="countdown-timer__values">
<span className="countdown-timer__values__days">{timer.days}</span>
{SEPARATOR}
<span className="countdown-timer__values__hours">{timer.hours}</span>
{SEPARATOR}
<span className="countdown-timer__values__minutes">
{timer.minutes}
</span>
{SEPARATOR}
<span className="countdown-timer__values__seconds">
{timer.seconds}
</span>
{SEPARATOR}
</div>
<div className="countdown-timer__units">
<span className="countdown-timer__units__days"> Days </span>
<span className="countdown-timer__units__hours"> Hrs </span>
<span className="countdown-timer__units__minutes"> Min </span>
<span className="countdown-timer__units__seconds"> Sec </span>
</div>
</div>
);
}
}
export default CountDownTimer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment