Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a simple countdown timer in React (https://www.seeleycoder.com/blog/react-countdown-timer)
// code used for https://www.seeleycoder.com/blog/react-countdown-timer
import * as React from 'react';
import PropTypes from 'prop-types';
// https://www.npmjs.com/package/countdown
import countdown from 'countdown';
const TimerSpanDisplay = function TimerSpanDisplay(props) {
const { className, value, label } = props;
return (
<div className={`timespan-display d-flex flex-column justify-content-center align-items-center px-2 px-sm-4 px-md-3 px-lg-3 px-xl-3 py-2 ${className || ''}`}>
<span className="timespan-value">{`${value.toString().padStart(2, '0')}`}</span>
<span className="timespan-label text-uppercase">{label}</span>
</div>
);
}
export class CountdownTimer extends React.Component {
constructor(props) {
super(props);
this.state = {
timespan: this.calculateTimespan(props.endDate)
};
}
componentDidMount() {
this._timerId = setInterval(() => {
this.setState({ timespan: this.calculateTimespan(this.props.endDate) });
}, 1000);
}
componentWillUnmount() {
if (!isNullOrUndefined(this._timerId))
clearInterval(this._timerId);
}
calculateTimespan(endDate) {
let now = new Date();
let timespan = countdown(now, endDate, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
return timespan;
}
render() {
const { timespan } = this.state;
return (
<div className={`bg-dark text-white d-flex justify-content-between w-100`}>
<TimerSpanDisplay className="ml-5 ml-md-0" value={timespan.days} label="Days" />
<TimerSpanDisplay value={timespan.hours} label="Hrs" />
<TimerSpanDisplay value={timespan.minutes} label="Min" />
<TimerSpanDisplay value={timespan.seconds} label="Sec" />
<div className="bg-black px-4 px-xl-3 py-1 d-flex align-items-center justify-content-center w-md-100 w-md-auto">
<i className="fal fa-angle-right fa-3x"></i>
</div>
</div>
);
}
}
// something like this:
var daysInSeconds = 24 * 60 * 60, // 86400 seconds
hoursInSeconds = 60 * 60, // 3600 seconds
minutesInSeconds = 60,
maxTimeLeft = 0;
var d, h, m, s;
// Number of days left
d = Math.floor(left / daysInSeconds);
left -= d * daysInSeconds;
// Number of hours left
h = Math.floor(left / hoursInSeconds);
left -= h * hoursInSeconds;
// Number of minutes left
m = Math.floor(left / minutesInSeconds);
left -= m * minutesInSeconds;
// Number of seconds left
s = left;
/* SCSS */
.timespan-display {
.timespan-value {
font-weight: bold;
font-size: 1.25rem;
}
.timespan-label {
font-size: 0.6875rem;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment