how the countdown timer shows two zeros in React + Typescript

Viewed 40

In my project I need to use a countdown timer for 2 minutes. In this project, React, TypeScript and ant design are used. I am using React version 18.2.0 . I designed this timer and it works properly, but it has a small problem. I just want it to show 09 instead of 9 for example when the numbers go below 10 (Like the photo below). I would be grateful if you could guide me. enter image description here

.timer{
  border: 1px solid red;
  padding: 1rem;
  width: 150px;
  height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


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

const [seconds, setSeconds] = useState<number>(59);
const [minutes, setMinutes] = useState<number>(1);

useEffect(() => {
    let timeInterval = setTimeout(() => {
      if (seconds > 0) {
        setSeconds(seconds - 1);
      }
      if (seconds === 0) {
        if (minutes === 0) {
          clearInterval(timeInterval);
        } else {
          setMinutes(minutes - 1);
          setSeconds(59);
        }
      }
    }, 1000);
    return ()=> {
      clearInterval(timeInterval);
    };
});

<div class="timer">
  <p>
    {minutes}:{seconds}
  </p>
</div>

1 Answers

According to me, you can make use of one/two useEffect(depending on your preference) statement and two more useStates to achieve this. The two new useStates would be the formattedSeconds and formattedMinutes. The useEffect runs when the seconds and minutes state changes and then, if they are less than 10, you add a leading zero to its string value. Otherwise, you simply return the same value. In the end, you display the newly created states instead of the ones you return and it will do the job. I wrote a piece of code to demonstrate this for a single number, but you can do the exact same thing for a second state value. The code:

export default function App() {
  const [number, setNumber] = useState(0);
  const [formattedNumber, setFormattedNumber] = useState("");
  useEffect(() => {
    if (number < 10) {
      const numberString = "0" + number.toString();
      setFormattedNumber(numberString);
      return;
    }
    const numberString = number.toString();
    setFormattedNumber(numberString);
  }, [number]);
  return (
    <div className="App">
      <input
        type="number"
        value={number}
        onChange={(e) => setNumber(e.target.value)}
      />
      <h1>{formattedNumber}</h1>
    </div>
  );
}

Hope this helps! Let me know if you need help with something.

Related