I’m building a loading bar in React, but something is not right. I want it to fill width 100%
once the timer is reached 3 seconds, but for some reason it does not work as expected.
const { useState, useEffect } = React;
const Loading = () => {
const [isLoading, setIsLoading] = useState(true);
const [progress, setProgress] = useState(0);
useEffect(() => {
const duration = 3000;
const increment = 100 / duration;
const timer = setInterval(() => {
setProgress((prevProgress) => {
const newProgress = prevProgress + increment;
if (newProgress >= 100) {
clearInterval(timer);
setIsLoading(false);
return 100;
}
return newProgress;
});
}, 10);
return () => clearInterval(timer);
}, []);
return (
<div className="canvas">
{isLoading && (
<div
className="loadng_bar"
style={{ width: `${progress}%` }}
></div>
)}
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Loading />
);
.loadng_bar {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 5px;
background-color: #c4483f;
transition: width 3.05s linear;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
It should increase the progress
up to full width during 3 seconds. How can I achieve it?