I am trying to design a perfect stopwatch. I have tried and it is working properly. But, I want the reset button to be disabled at initial stage and when the count had begin by using start button reset should be enabled.
``
import React, { useState, useEffect } from 'react';
import './Stopwatch.css';
function Stopwatch() {
const [status, setStatus] = useState('start');
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const [intervalId, setIntervalId] = useState(null);
useEffect(() => {
if (!isRunning) {
clearInterval(intervalId);
}
}, [isRunning, intervalId]);
function start() {
setIsRunning(true);
setStatus ('running');
let startTime = Date.now() - time;
let id = setInterval(() => {
setTime(Date.now() - startTime);
}, 10);
setIntervalId(id);
}
function pause() {
setStatus('paused');
setIsRunning(false);
}
function resume() {
setIsRunning(true);
setStatus('running');
let startTime = Date.now() - time;
let id = setInterval(() => {
setTime(Date.now() - startTime);
}, 10);
setIntervalId(id);
}
function reset() {
setTime(0);
setStatus('start');
setIsRunning(false);
}
let hours = Math.floor((time / (1000 * 60 * 60)) % 24);
let minutes = Math.floor((time / (1000 * 60)) % 60);
let seconds = Math.floor((time / 1000) % 60);
return (
<div>
<h1>
<h1><b>React Stopwatch</b></h1>
{hours < 10 ? '0' + hours : hours}:
{minutes < 10 ? '0' + minutes : minutes}:
{seconds < 10 ? '0' + seconds : seconds}
</h1>
{isRunning ?(
<>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset</button>
</>
):
(status ==='start'?(
<>
<button onClick={start}>Start</button>
<button onClick={reset}>Reset</button>
</>) : ( <>
<button onClick={resume}>Resume</button>
<button onClick={reset}>Reset</button>
</>)
) }
</div>
);
}
export default Stopwatch;
`
`
I want the reset button to be disabled at initial stage and when the count had begin by using start button reset should be enabled.
You can use the disabled
attribute on the button
wherever you want to disable it.
In your case, you can disable it when time
is 0
when the status
is start
.
<button onClick={reset} disabled={time === 0}>Reset</button>