React countdown timer using new Date()

Asked
Active3 hr before
Viewed126 times

11 Answers

timerusingreact
90%

Step 4 — Updating Your App State with useState and useEffect ,To use the current year instead of hard coding 2020, you can create a new state variable and set the initial state to new Date().getFullYear();.,At the top of the App.js file, add useState and useEffect in your import statement:

To start, make a new project. In your terminal, run the following script to install a fresh project using create-react-app:

npx create - react - app react - hooks - counter
load more v
88%

 Pretag team - issue, fix, solve, resolve
72%

I think you are making it way more complicated than it needs to be.,Store a state of a 5 minute countdown (in seconds) and a second piece of state to start/run the timer.,When the timer is started seed the countdown state with 5 minutes (it will expire from the current point in time).

function App() {
  const [countDown, setCountDown] = React.useState(0);
  const [runTimer, setRunTimer] = React.useState(false);

  React.useEffect(() => {
    let timerId;

    if (runTimer) {
      setCountDown(60 * 5);
      timerId = setInterval(() => {
        setCountDown((countDown) => countDown - 1);
      }, 1000);
    } else {
      clearInterval(timerId);
    }

    return () => clearInterval(timerId);
  }, [runTimer]);

  React.useEffect(() => {
    if (countDown < 0 && runTimer) {
      console.log("expired");
      setRunTimer(false);
      setCountDown(0);
    }
  }, [countDown, runTimer]);

  const togglerTimer = () => setRunTimer((t) => !t);

  const seconds = String(countDown % 60).padStart(2, 0);
  const minutes = String(Math.floor(countDown / 60)).padStart(2, 0);

  return (
    <div className="App">
      <div>
        Time: {minutes}:{seconds}
      </div>

      <button type="button" onClick={togglerTimer}>
        {runTimer ? "Stop" : "Start"}
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />,
  rootElement
);
load more v
65%

Try using this example:

import React, { useState, useEffect } from "react";

function calcDiffInMinutes(dateA, dateB) {
  return Math.floor(((dateA.getTime() - dateB.getTime()) / 1000) % 60); // TODO CALCULATIONS HERE
}

export default ({ dateFrom }) => {
  const [currentDate, setCurrentDate] = useState(new Date());
  const [minutesDiff, setMinutesDiff] = useState(
    calcDiffInMinutes(currentDate, dateFrom)
  );

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      setCurrentDate(new Date());
    }, 1000);

    return () => clearTimeout(timeoutId);
  }, [currentDate]);

  useEffect(() => {
    setMinutesDiff(calcDiffInMinutes(currentDate, dateFrom));
  }, [currentDate, dateFrom]);

  return (
    <div>
      <div>Date From: {dateFrom.toISOString()}</div>
      <div>CountDown value: {minutesDiff}</div>
    </div>
  );
};
75%

options The options object consists of the following three component props and is used to customize the time delta object's formatting:,This is one of React's internal component props and is used to identify the component. However, we can leverage this behavior and use it to, for example, restart the countdown by passing in a new string or number.,onStart is a callback and triggered whenever the countdown is started (including first-run). It receives the time delta object, which is returned by calcTimeDelta.

npm install react - countdown--save
load more v
40%

 Pretag team - issue, fix, solve, resolve
22%

the final date or then,When we have these 2 dates, we can subtract now from then using moment and we'll get the remaining time (or the countdown value).,the current date or now

import moment from 'moment';

const then = moment(timeTillDate, timeFormat);
const now = moment();
const countdown = moment(then - now);
load more v
60%

Example: Now lets see how to create a countdown timer in Reactjs. The code for App.js will look like the following.,How to create a simple Responsive Footer in React JS ?,How to create a Read More component in ReactJS?

Step 1: Create a React application using the following command:

npx create - react - app foldername
load more v
48%

In this article, we’ll look at how to create a countdown timer app with React and JavaScript.,To create the countdown timer app, we write:,In the App component, we call setInterval to call setDiff to set the date and time difference every second.

To install it, we run:

npx create - react - app countdown - timer
load more v
23%

First up in the CountdownTimer function we need to define the end of the countdown. With this defined we then calculate the time remaining using the JavaScript Date() object:,Next create a new file called CountdownTimer.js with the imports and primary function:,In this tutorial we’ll be building a custom countdown timer component in React. This type of component can be used to display the time remaining until a big event, festival or special occasion. In this instance we’ll be building a countdown timer for the New Year.

Let’s get started by setting up a new project using Create React App:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
npx create - react - app countdown - timer
load more v
90%

So, without further ado, here’s how to make your own countdown clock in a mere 18 lines of JavaScript.,First, we’re creating a variable total, to hold the remaining time until the deadline. The Date.parse() function converts a time string into a value in milliseconds. This allows us to subtract two times from each other and get the amount of time in between.,Repeat this logic to convert the milliseconds to minutes, hours, and days.

The ISO 8601 format:

const deadline = '2015-12-31';
load more v

Other "timer-using" queries related to "React countdown timer using new Date()"