Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Using setTimeouts in React Components
Next article icon

Event Countdown Timer Using React

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Event Countdown Timer is an application where you can create an event with the name, date, and category of the event and it will create a card that will show you the remaining time of the event. After reaching that time of the day it will notify you.

The application will provide the option to start, stop and pause the countdown timer . Project will contain elegant UI to display countdown timer . So lets start building it.

Preview of Final Output:

Event Countdown Timer Using React

Prerequisites and Technologies:

  • React
  • Bootstrap
  • JSX

Approach:

We will build a single-page application in React that will display a countdown timer on the home page. The event countdown timer will be created as a separate component in React. The component is then rendered in app file. Bootstrap will be added to display options for an event countdown timer. The timer will start by taking time as input from the user.

Functionalities:

  • Add Timer: This will add multiple countdown timers as required. set Title , Category and time of countdown timer.
  • Remove Timer: This will remove a countdown timer.
  • Calculate Time: The calculateTimeRemaining will calculate remaining time for each timer.
  • Format Time: The formatTime will convert time in seconds to Days, Hours , Minutes and Seconds .
  • Add Time: The addTimer and removeTimer will add and remove timers respectively by updating timers state.

Finally we will use useEffect to set interval with time . Time will be updated in the interval itself . when time reaches 0 the isRunning state is set to false. Thats it now we can add render code . The render code will consist of input field for taking time as input in seconds. This will update time state in our code . Then we will display current time in division . Three buttons will be used for three functionalities respectively .

Steps to create the application:

Step 1: First we need to create react app using below command

npx create-react-app <<Project_Name>>

Step 2: Navigate to the folder

cd <<Project_Name>>

Step 3: Install bootstrap for css using below command.

npm install bootstrap

Step 4: Create a folder components in src directory and inside the folder create files Countdown.js and Countdown.css

Project Structure:

Screenshot-(75)

Example: Here we we have created two JS file App.js, Countdown.js and CSS file to style the interface.

CSS
body {     background-color: rgb(230, 227, 223); }  .main-container {     display: flex;     flex-direction: column;     justify-content: center;     align-items: center;     height: auto; }  .timers {     height: fit-content;     margin: auto;     display: flex;     justify-content: space-around;     flex-wrap: wrap; }  .card {     display: flex;     flex-direction: column; } 
JavaScript
// src/App.js  import './App.css'; import Countdown from './components/Countdown';  function App() {   return (     <div className="App">       <Countdown />     </div>   ); }  export default App; 
JavaScript
// src/components/Countdown.js import React, { useState, useEffect } from "react"; import "bootstrap/dist/css/bootstrap.css"; import "./Countdown.css";  function Countdown() {     const [timers, setTimers] = useState([]);     const [newTimerTitle, setNewTimerTitle] = useState("");     const [newTimerCategory, setNewTimerCategory] = useState("");     const [newTimerDateTime, setNewTimerDateTime] = useState("");      const categoryColors = {         Meeting: "bg-primary",         Birthday: "bg-danger",         Reminder: "bg-success",     };      useEffect(() => {         const intervalIds = {};          const updateTimers = () => {             setTimers((prevTimers) =>                 prevTimers.map((timer) => {                     const targetTime = new Date(timer.targetDateTime)                                        .getTime();                     const currentTime = new Date().getTime();                     const timeRemaining = Math.max(                         Math.floor((targetTime - currentTime) / 1000),                         0                     );                      if (timeRemaining === 0) {                         clearInterval(intervalIds[timer.id]);                         return {                          ...timer, isRunning: false, timeRemaining: 0 };                     }                      return { ...timer, timeRemaining };                 })             );         };          timers.forEach((timer) => {             if (timer.isRunning && timer.timeRemaining > 0) {                 intervalIds[timer.id] = setInterval(updateTimers, 1000);             }         });          return () => {             Object.values(intervalIds).forEach((intervalId) =>                 clearInterval(intervalId)             );         };     }, [timers]);      const removeTimer = (timerId) => {         setTimers((prevTimers) =>             prevTimers.filter((timer) => timer.id !== timerId)         );     };      const calculateTimeRemaining = (targetTime) => {         const currentTime = new Date().getTime();         const timeDifference = targetTime - currentTime;         const secondsRemaining =                  Math.max(Math.floor(timeDifference / 1000), 0);         return secondsRemaining;     };      const formatTimeRemaining = (seconds) => {         const days = Math.floor(seconds / (3600 * 24));         const hours = Math.floor((seconds % (3600 * 24)) / 3600);         const minutes = Math.floor((seconds % 3600) / 60);         const remainingSeconds = seconds % 60;          return {             days,             hours,             minutes,             seconds: remainingSeconds,         };     };      const addTimer = () => {         if (!newTimerTitle || !newTimerCategory || !newTimerDateTime)              return;                      // Convert to milliseconds since epoch         const targetDateTime = new Date(newTimerDateTime).getTime();                   const newTimer = {             id: timers.length + 1,             category: newTimerCategory,             targetDateTime,             // Calculate time remaining here             timeRemaining: calculateTimeRemaining(targetDateTime),              isRunning: true,             title: newTimerTitle,             showTitleInput: false,         };          setTimers([...timers, newTimer]);          setNewTimerTitle("");         setNewTimerCategory("");         setNewTimerDateTime("");     };      return (         <div className="countdown-container">             <div className="main-container">                 <div className="input-container m-3">                     <h1 className="text-center text-success">                         GeeksForGeeks Countdown Timer                     </h1>                     <input                         type="text"                         className="form-control m-2"                         placeholder="Timer Title"                         value={newTimerTitle}                         onChange={                             (e) => setNewTimerTitle(e.target.value)                         }                     />                     <select                         className="form-select m-2"                         value={newTimerCategory}                         onChange={                             (e) => setNewTimerCategory(e.target.value)                         }                     >                         <option value="">Select a Category</option>                         <option value="Meeting">Meeting</option>                         <option value="Birthday">Birthday</option>                         <option value="Reminder">Reminder</option>                     </select>                     <input                         className="form-control m-2"                         type="datetime-local"                         value={newTimerDateTime}                         onChange={                             (e) => setNewTimerDateTime(e.target.value)                         }                     />                     <button                         className="btn btn-primary m-2"                         onClick={addTimer}                         disabled={                             !newTimerTitle ||                             !newTimerCategory ||                             !newTimerDateTime                         }                     >                         Add Timer                     </button>                 </div>                 <div className="timers-div m-auto d-flex">                     {timers.map((timer) => {                         const timeRemaining = formatTimeRemaining(                             timer.timeRemaining                         );                          return (                             <div                                 key={timer.id}                                 className={`card m-4 ${                                     categoryColors[timer.category] || ""                                 }`}                             >                                <h3 className="card-title m-2 text-light">                                     {timer.title}                                </h3>                                 <h4 className="card-title m-2 text-dark">                                     {timer.category}                                 </h4>                                 <div className="card-body d-flex">                                     {timeRemaining.days > 0 && (                                         <div className="container                                                          bg-light                                                          text-dark                                                          rounded m-2">                                             <div>                                                 <h1>                                                     <strong>                                                     {timeRemaining.days}                                                     </strong>                                                 </h1>                                             </div>                                             <div>days </div>                                         </div>                                     )}                                     <div className="container bg-light                                      text-dark rounded m-2">                                         <div>                                             <h1>                                                 <strong>                                                     {timeRemaining.hours}                                                 </strong>                                             </h1>                                         </div>                                         <div>hours </div>                                     </div>                                     <div className="container                                                      bg-light                                                      text-dark                                                      rounded m-2">                                         <div>                                             <h1>                                                 <strong>                                                 {timeRemaining.minutes}                                                 </strong>                                             </h1>                                         </div>                                         <div>minutes </div>                                     </div>                                     <div className="container                                                      bg-light                                                      text-dark                                                      rounded m-2">                                         <div>                                             <h1>                                                 <strong>                                                 {timeRemaining.seconds}                                                 </strong>                                             </h1>                                         </div>                                         <div>seconds </div>                                     </div>                                 </div>                                 <button                                     className="btn btn-dark m-2"                                     onClick={() => removeTimer(timer.id)}                                     disabled={timer.timeRemaining <= 0}                                 >                                     Remove                                 </button>                             </div>                         );                     })}                 </div>             </div>         </div>     ); }  export default Countdown; 

Steps to run the application:

Step 1: Open terminal in project folder and run below command

npm start

Step 2: Open the following link in your browser

http://localhost:3000/

Output:


Next Article
Using setTimeouts in React Components

D

deepcodr
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Web Development Projects
  • ReactJS-Projects
  • Geeks Premier League 2023

Similar Reads

  • How to Create Countdown Timer using React Native ?
    Our main objective focuses on constructing a straightforward and use­r-friendly countdown timer that impeccably showcase­s the remaining time le­ft in terms of years, days, hours, minutes, and seconds until a specific date. To set up your de­velopment environment, begin by installing Node.js. Next,
    4 min read
  • Event Calendar using React
    The Event calender using react basically displays a calendar with the additional feature of adding an event on a particular date by selecting it. User can also delete the event if he/she wants to delete it. All this logic of event creation and deletion is implemented using JSX. This project is usefu
    7 min read
  • How to Create Countdown Timer in React JS
    React timers are very common UI components that are widely used in various applications and websites to visually display the remaining time for a specific activity or event. React timers are mostly used to highlight the commencement or conclusion of events or offers on commercial websites. This tuto
    8 min read
  • Using setTimeouts in React Components
    The setTimeout method in React enables the execution of a function after a specified time interval. This functionality is pivotal in web development for implementing time-based behaviors, offering a spectrum of applications ranging from user interface enhancements to asynchronous operations. The set
    6 min read
  • Time Format Converter using ReactJS
    In this article, we will develop a Time Format Converter Project application using the ReactJS library. A Time Format Converter is a React-based tool that allows users to convert between 12-hour and 24-hour time formats. It validates input, performs the conversion, and displays the result or error m
    7 min read
  • Appointment Management System using React
    The Appointment Management System is a web application that allows users to schedule, manage, and view appointments. It provides an easy-to-use interface for clients to book and keep track of appointments. Below is a simplified outline for creating an Appointment Management System using React JS. Pr
    5 min read
  • Flutter - Countdown Timer
    The countdown timer app is about setting a time that moves in reverse order, as it shows the time left in the upcoming event. A countdown timer is an accurate timer that can be used for a website or blog to display the countdown to any special event, such as a birthday or anniversary. Step-by-Step I
    3 min read
  • Tip Calculator using React
    In this article, we will create a Tip Calculator using ReactJS. This project basically implements functional components and manages the state accordingly using the useState and useEffect hook of ReactJS. The user enters the Bill Amount, Tip Percentage and the number of persons then the output will r
    6 min read
  • Timeline Component in React.js
    Timelines are often used in user interfaces to illustrate a step-by-step procedure. It can describe to the user which stage of the process they currently are and what the further tasks are. Material UI labs module provide a Timeline component along with some other utility components to make this ver
    3 min read
  • How to implement toggle using ReactJS ?
    Toggles are a common UI element used to switch between two states or options in a user interface. In ReactJS, it can be achieved using state management and event handling. In this article, we will explore how to implement a toggle feature using ReactJS. PrerequisitesState management in ReactEvent Ma
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences