So I'm trying to build progress bar and convert minutes to % so I can apply them to the progress below. When the time is 00 then the progress should be 100% filled (or the opposite not filled, doesn't matter)
Here is what I've build until now:
import * as styles from './Screen.module.scss'
import { useState, useEffect } from 'react'
export default function Screen() {
const [countDown, setCountDown] = useState(0);
const [runTimer, setRunTimer] = useState(true);
useEffect(() => {
let timerId;
if (runTimer) {
setCountDown(60 * 5);
timerId = setInterval(() => {
setCountDown((countDown) => countDown - 1);
}, 1000);
} else {
clearInterval(timerId);
}
return () => clearInterval(timerId);
}, [runTimer]);
useEffect(() => {
if (countDown < 0 && runTimer) {
console.log("expired");
setRunTimer(false);
setCountDown(0);
}
}, [countDown, runTimer]);
const seconds = String(countDown % 60).padStart(2, 0);
const minutes = String(Math.floor(countDown / 60)).padStart(2, 0);
const [prg, setPrg] = useState(0);
const fill = {
width: `${prg}%`,
height: '100%',
backgroundColor: 'green',
transform: 'width 0.45s ease-in-out'
}
return (
<main className={styles.container}>
<div className={styles.bar}>
<div className={styles.bar_value}>{minutes}:{seconds}</div>
<div style={fill}></div>
</div>
</main>
)
}
CodePudding user response:
prg
shouldn't be state, since it's derived solely from the duration of your countdown and the number of seconds left. (You might want to make 60 * 5
a constant, a prop, or state though.)
Simply:
const prg = (countDown / (60 * 5)) * 100;
will have your progress bar count down from 100% to 0%.
To have it count up,
const prg = 100 - (countDown / (60 * 5)) * 100;