ComponentsCountdown Timer

Credit goes to alberduris for re-creating this ShipFast component.

Table of Contents:

A countdown timer showing days, hours, minutes, and seconds left. Can be used for counting down till Product Hunt launch.

Countdown Timer Component

Code

/components/CountdownTimer.js

1"use client";
2
3import { useState, useEffect } from "react";
4
5const CountdownTimer = ({ initialTimeLeft }) => {
6  const [timeLeft, setTimeLeft] = useState(initialTimeLeft);
7
8  const calculateTimeLeft = () => {
9    const difference = +new Date("2024-12-08") - +new Date();
10    let timeLeft = { days: 0, hours: 0, minutes: 0, seconds: 0 };
11
12    if (difference > 0) {
13      timeLeft = {
14        days: Math.floor(difference / (1000 * 60 * 60 * 24)),
15        hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
16        minutes: Math.floor((difference / 1000 / 60) % 60),
17        seconds: Math.floor((difference / 1000) % 60), // Calculate seconds
18      };
19    }
20
21    return timeLeft;
22  };
23
24  useEffect(() => {
25    const timer = setTimeout(() => {
26      setTimeLeft(calculateTimeLeft());
27    }, 1000); // Update every second
28    return () => clearTimeout(timer); // Clear the timer on component unmount
29  }, [timeLeft]);
30
31  return (
32    <div className="flex items-center justify-center gap-4 text-center">
33      <div>
34        <p className="mb-2 text-base text-gray-600 dark:text-gray-400">
35          The Starter Kit is launching soon...
36        </p>
37        <div className="flex gap-4 rounded-lg bg-white p-3 text-center shadow-lg md:p-4 dark:bg-primary">
38          <div>
39            <p className="text-lg font-extrabold text-gray-900 dark:text-gray-100">
40              {timeLeft.days}
41            </p>
42            <p className="text-gray-900 dark:text-gray-100">Days</p>
43          </div>
44          <div>
45            <p className="text-lg font-extrabold text-gray-900 dark:text-gray-100">
46              {timeLeft.hours}
47            </p>
48            <p className="text-gray-900 dark:text-gray-100">Hours</p>
49          </div>
50          <div>
51            <p className="text-lg font-extrabold text-gray-900 dark:text-gray-100">
52              {timeLeft.minutes}
53            </p>
54            <p className="text-gray-900 dark:text-gray-100">Minutes</p>
55          </div>
56          <div>
57            <p className="text-lg font-extrabold text-gray-900 dark:text-gray-100">
58              {timeLeft.seconds}
59            </p>
60            <p className="text-gray-900 dark:text-gray-100">Seconds</p>
61          </div>
62        </div>
63      </div>
64    </div>
65  );
66};
67
68export default CountdownTimer;

Usage

/components/Pricing.js

1import CountdownTimer from "./CountdownTimer";
2
3const Pricing = () => {
4  return (
5    <>
6      <section>
7        ...
8        <CountdownTimer initialTimeLeft={10} />
9        ...
10      </section>
11    </>
12  );
13};
14
15export default Pricing;