Skip to content

Craft a Timepiece with ReactJS

Comprehensive Learning Hub: Our educational platform encompasses a vast array of subjects, including computer science, programming, school education, vocational training, commerce, software tools, competitive exam preparation, and more, empowering learners in diverse fields.

Develop a Stopwatch utilizing ReactJS programming
Develop a Stopwatch utilizing ReactJS programming

Craft a Timepiece with ReactJS

**Creating a Stopwatch in ReactJS**

A new project, part of the ReactJS-Projects series, allows users to create a functional stopwatch with Start, Pause, Resume, and Reset capabilities. This project structure organises components and dependencies for a seamless development experience.

---

### Project Structure

The project structure is as follows:

``` stopwatch-react/ │ ├── public/ │ └── index.html │ ├── src/ │ ├── components/ │ │ └── Stopwatch.js # Stopwatch component with timer logic │ ├── App.js # Main app rendering Stopwatch │ ├── index.js # React entry point │ └── styles.css # Optional CSS for styling │ ├── package.json └── README.md ```

---

### Components Used

- **Stopwatch.js** — main component that: - Displays timer (hours, minutes, seconds, milliseconds) - Controls Start, Pause, Resume, Reset buttons - Updates time using an interval

- **App.js** — simple wrapper rendering Stopwatch

---

### Step-by-Step Implementation

#### 1. Stopwatch Component (Stopwatch.js)

```jsx import React, { useState, useEffect, useRef } from 'react';

const Stopwatch = () => { const [time, setTime] = useState(0); // time in milliseconds const [isRunning, setIsRunning] = useState(false); const [isPaused, setIsPaused] = useState(false);

const intervalRef = useRef(null);

useEffect(() => { if (isRunning && !isPaused) { // Start timer updates every 10 ms for smooth milliseconds count intervalRef.current = setInterval(() => { setTime(prevTime => prevTime + 10); }, 10); } else { clearInterval(intervalRef.current); }

// Cleanup on unmount or when dependencies change return () => clearInterval(intervalRef.current); }, [isRunning, isPaused]);

const formatTime = (ms) => { const milliseconds = Math.floor((ms % 1000) / 10); const seconds = Math.floor((ms / 1000) % 60); const minutes = Math.floor((ms / (1000 * 60)) % 60); const hours = Math.floor(ms / (1000 * 60 * 60));

return `${hours.toString().padStart(2, '0')}: ${minutes.toString().padStart(2, '0')}: ${seconds.toString().padStart(2, '0')}. ${milliseconds.toString().padStart(2, '0')}`; };

// Button handlers const handleStart = () => { setIsRunning(true); setIsPaused(false); };

const handlePause = () => { setIsPaused(true); };

const handleResume = () => { if (isRunning && isPaused) setIsPaused(false); };

const handleReset = () => { setIsRunning(false); setIsPaused(false); setTime(0); };

return (

{formatTime(time)} {!isRunning && } {isRunning && !isPaused && } {isRunning && isPaused && } ); };

export default Stopwatch; ```

---

#### 2. App Component (App.js)

```jsx import React from 'react'; import Stopwatch from './components/Stopwatch';

function App() { return (

); }

export default App; ```

---

#### 3. Entry Point (index.js)

```jsx import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import './styles.css'; // optional styling

const root = ReactDOM.createRoot(document.getElementById('root')); root.render(); ```

---

### How to Run the Application

1. **Initialize Project** Use Create React App for quick setup:

``` npx create-react-app stopwatch-react cd stopwatch-react ```

2. **Add Stopwatch Component** Create `src/components/Stopwatch.js` and paste the Stopwatch code above.

3. **Replace src/App.js and src/index.js** Update these files with the code provided above.

4. **Optional Styling** Add `src/styles.css` for basic styling if desired (or inline styles as shown).

5. **Start Development Server** ``` npm start ```

6. **Open in Browser** Visit `http://localhost:3000` to use the stopwatch app.

---

### Explanation

- We store time in milliseconds and update it every 10ms using `setInterval` for smooth timer behavior. - `isRunning` and `isPaused` states control the timer's lifecycle for start, pause, and resume. - The `formatTime` function converts milliseconds to `HH:MM:SS.MS` string format. - Buttons dynamically change visibility depending on the stopwatch state. - Clean up intervals in `useEffect` cleanup to avoid memory leaks or multiple intervals.

This architecture is simple, clear, and uses modern React hooks for state and side effects management.

---

If you need any code elaboration or additional features (like lap-times), let me know! The Timer, ControlButtons, and their respective CSS files are also part of the project. In the StopWatch component, there are three states: time, isActive, and isPaused. After creating the project folder, move to it using the command provided in Step 2. The ControlButtons component changes its rendering based on whether the stop watch has been started. To create a React application, use the command provided in Step 1.

The project structure incorporates a technology stack that includes ReactJS for building the user interface, and JavaScript for implementing the logic. In the implementation of the component, the Math module is used to format the time display accurately. This project serves as an instance of integrating math and technology, as it creates a sophisticated ReactJS Stopwatch component.

Read also:

    Latest