I am relatively new at ReactJS. So, I’ve been trying to create a countdown using React, which I managed to do, but it returns this
Essentially, I don’t want the colon after the ‘seconds’.
This is my code for the countdown.
JavaScript
x
35
35
1
const calculateTimeLeft = () => {
2
let year = new Date().getFullYear();
3
const difference = +new Date(`${year}-02-21`) - +new Date();
4
let timeLeft = {};
5
6
if (difference > 0) {
7
timeLeft = {
8
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
9
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
10
minutes: Math.floor((difference / 1000 / 60) % 60),
11
seconds: Math.floor((difference / 1000) % 60),
12
};
13
}
14
return timeLeft;
15
};
16
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());
17
const [year] = useState(new Date().getFullYear());
18
19
useEffect(() => {
20
setTimeout(() => {
21
setTimeLeft(calculateTimeLeft());
22
}, 1000);
23
});
24
25
const timerComponents = [];
26
27
Object.keys(timeLeft).forEach((interval) => {
28
if (!timeLeft[interval]) {
29
return;
30
}
31
timerComponents.push(
32
<span>{timeLeft[interval]}{" : "}</span>
33
);
34
});
35
Would really appreciate the help thanks!
Advertisement
Answer
JavaScript
1
14
14
1
const keyCount = Object.keys(timeLeft).length;
2
3
Object.keys(timeLeft).forEach((interval, index) => { // Here, I added index
4
if (!timeLeft[interval]) {
5
return;
6
}
7
timerComponents.push(
8
<span>
9
{timeLeft[interval]}
10
{index === (keyCount-2) ? '' : ' : '} // Here
11
</span>
12
);
13
});
14