Stopwatches are commonly used in various applications to measure time intervals with precision and this question is also asked in many frontend interviews. In this tutorial, we’ll walk through the process of creating a simple stopwatch application using ReactJS. We’ll cover the basic components, state management, and event handling required to build this stopwatch.
Setting Up the Project
1. Create a New React App:
Follow the same steps as mentioned in the previous examples to create a new React app named “StopwatchApp”.
2. Navigate to the App Directory: Change into the app directory:
cd StopwatchApp
3. Starting the Development Server: Start the development server:
npm start
Building the Stopwatch Component
1. Remove Default Files: Clear the contents of `App.js` and remove the unnecessary files, as explained in the previous examples.
2. Create a Stopwatch.js File: Inside the `src` folder, create a new file named `Stopwatch.js`.
3. Implement the Stopwatch Component:
In the `Stopwatch.js` file, use the following code to create the stopwatch component displaying time in hours, minutes, and seconds:
import React, { useState, useRef } from 'react';
import './Stopwatch.css';
const Stopwatch = () => {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const timerRef = useRef();
const formatTime = timeInSeconds => {
const hours = Math.floor(timeInSeconds / 3600);
const minutes = Math.floor((timeInSeconds % 3600) / 60);
const seconds = timeInSeconds % 60;
return `${hours.toString().padStart(2, '0')} : ${minutes
.toString()
.padStart(2, '0')} : ${seconds.toString().padStart(2, '0')}`;
};
const handleStart = () => {
if (!isRunning) {
setIsRunning(true);
timerRef.current = setInterval(() => {
setTime(prevTime => prevTime + 1);
}, 1000);
}
};
const handleStop = () => {
clearInterval(timerRef.current);
setIsRunning(false);
};
const handleReset = () => {
clearInterval(timerRef.current);
setTime(0);
setIsRunning(false);
};
return (
<div className="stopwatch">
<h1>Stopwatch App</h1>
<p>Time: {formatTime(time)}</p>
<button onClick={handleStart} disabled={isRunning}>
Start
</button>
<button onClick={handleStop} disabled={!isRunning}>
Stop
</button>
<button onClick={handleReset}>Reset</button>
</div>
);
};
export default Stopwatch;
Integrating the Stopwatch Component
1. Update App.js:
In the `src` folder, open the `App.js` file and import the `Stopwatch` component:
import React from 'react';
import Stopwatch from './Stopwatch';
function App() {
return (
<div className="App">
<Stopwatch />
</div>
);
}
export default App;
Output:
Styling the Stopwatch
You can create a `Stopwatch.css` file inside the `src` folder and define your styling rules to customize the appearance of the stopwatch.
Conclusion
You’ve successfully created a stopwatch application displaying time in hours, minutes, and seconds. This blog tutorial demonstrates how to format the time and integrate it with the functional component structure using React Hooks.