StopWatch use React - TechXplore

Saturday, 23 December 2023

StopWatch use React

 StopWatch React:

I have created the simple  StopWatch app using React and style added the css.





stopwatch.js

import React, { Component } from 'react';

import './timer.css';


class Stopwatch extends Component {

  constructor(props) {

    super(props);

    this.state = {

      hours: 0,

      minutes: 0,

      seconds: 0,

      milliseconds: 0,

      isRunning: false,

      isPaused: false,

    };

  }

  handleStartStop = () => {

    this.setState(

      (prevState) => ({

        isRunning: !prevState.isRunning,

        isPaused: false,

      }),

      () => {

        if (this.state.isRunning) {

          this.timer = setInterval(() => {

            this.setState((prevState) => {

              const currentTime = prevState.hours * 3600 + prevState.minutes * 60 + prevState.seconds + prevState.milliseconds / 1000;

              const newTime = currentTime + 0.1; // Increment by 0.1 seconds

              return {

                hours: Math.floor(newTime / 3600),

                minutes: Math.floor((newTime % 3600) / 60),

                seconds: Math.floor(newTime % 60),

                milliseconds: Math.floor((newTime % 1) * 1000),

              };

            });

          }, 100);

        } else {

          clearInterval(this.timer);

        }

      }

    );

  };

  

 handlePause = () => {

    this.setState({

      isRunning: false,

      isPaused: true,

    });

    clearInterval(this.timer);

  };


  handleReset = () => {

    this.setState({

      hours: 0,

      minutes: 0,

      seconds: 0,

      milliseconds: 0,

      isRunning: false,

      isPaused: false,

    });

    clearInterval(this.timer);

  };


  componentWillUnmount() {

    clearInterval(this.timer);

  }


  render() {

    const { hours, minutes, seconds, milliseconds } = this.state;

    return (

      <div className="stopwatch-container">

        <div className="time">

          {String(hours).padStart(2, '0')}:{String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}:{String(milliseconds).padStart(3, '0')}

        </div>

        <div className="buttons">

          <button onClick={this.handleStartStop} className='Start-time'>

            {this.state.isRunning ? 'Stop' : 'Start'}

          </button>

         

          <button onClick={this.handleReset} className='Reset-time'>Reset</button>

        </div>

      </div>

    );

  }

}

export default Stopwatch;

Stopwatch.css:
.stopwatch-container {
   text-align: center;
   margin: 50px auto;
 }
 
 .time {
   font-size: 7em;
   font-weight: bold;
   font-family: sans-serif;
   
   margin-bottom: 20px;
 }
 .Start-time{
 padding:59px 50px;
 margin: 15px;
border: none;
font-size: 1em;
font-weight: bold;
color: white;
background-color:rgb(43, 239, 8);
cursor: pointer;
border-radius: 110px;
}
.Start-time:hover{
   background-color: rgb(103, 245, 90);
   color: black;
}
.Reset-time{
padding: 60px 50px;
margin: 15px;
border: none;
font-size: 0.9em;
font-weight: bold;
color:white;
background-color: rgb(251, 4, 4);
cursor: pointer;
border-radius: 110px;
}
.Reset-time:hover{
  background-color: rgb(242, 97, 97);
  color: black;
}

app.js:
import Stopwatch from "./timer";

function App(){ 
  return (
   <Stopwatch/>
  );
}

export default App;

OutPut:


State:
The component has a state that tracks various properties of the stopwatch:

hours: The number of hours in the stopwatch.
minutes: The number of minutes in the stopwatch.
seconds: The number of seconds in the stopwatch.
milliseconds: The number of milliseconds in the stopwatch.
isRunning: A boolean indicating whether the stopwatch is currently running.


Constructor:
In the constructor, the initial state is set, with all time-related properties initialized to 0, and the flags for running and paused set to false.


constructor(props) {
  super(props);
  this.state = {
    hours: 0,
    minutes: 0,
    seconds: 0,
    milliseconds: 0,
    isRunning: false,
    isPaused: false,
  };
}

handleStartStop:
The handleStartStop method is responsible for toggling the start and stop functionality of the stopwatch. When the user clicks the "Start" button, it sets up a timer using setInterval to increment the time every 0.1 seconds. The time is calculated in seconds, and the state is updated accordingly.

handleStartStop = () => {
  this.setState(
    (prevState) => ({
      isRunning: !prevState.isRunning,
      isPaused: false,
    }),
    () => {
      if (this.state.isRunning) {
        this.timer = setInterval(() => {
          this.setState((prevState) => {
            const currentTime = prevState.hours * 3600 + prevState.minutes * 60 + prevState.seconds + prevState.milliseconds / 1000;
            const newTime = currentTime + 0.1; // Increment by 0.1 seconds
            return {
              hours: Math.floor(newTime / 3600),
              minutes: Math.floor((newTime % 3600) / 60),
              seconds: Math.floor(newTime % 60),
              milliseconds: Math.floor((newTime % 1) * 1000),
            };
          });
        }, 100);
      } else {
        clearInterval(this.timer);
      }
    }
  );
};

handlePause:
The handlePause method is responsible for pausing the stopwatch. It sets the isRunning flag to false and the isPaused flag to true. It also clears the interval timer.

handlePause = () => {
  this.setState({
    isRunning: false,
    isPaused: true,
  });
  clearInterval(this.timer);
};
handleReset:
The handleReset method resets all time-related properties to 0 and stops the timer by clearing the interval.


handleReset = () => {
  this.setState({
    hours: 0,
    minutes: 0,
    seconds: 0,
    milliseconds: 0,
    isRunning: false,
    isPaused: false,
  });
  clearInterval(this.timer);
};
componentWillUnmount:
The componentWillUnmount lifecycle method is used to clear the interval when the component is about to be unmounted to prevent memory leaks.


componentWillUnmount() {
  clearInterval(this.timer);
}
render:
The render method displays the current time and buttons for starting, pausing, and resetting the stopwatch.


render() {
  const { hours, minutes, seconds, milliseconds } = this.state;
  return (
    <div className="stopwatch-container">
      <div className="time">
        {String(hours).padStart(2, '0')}:{String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}:{String(milliseconds).padStart(3, '0')}
      </div>
      <div className="buttons">
        <button onClick={this.handleStartStop}>
          {this.state.isRunning ? 'Stop' : 'Start'}
        </button>
        <button onClick={this.handlePause} disabled={!this.state.isRunning || this.state.isPaused}>
          Pause
        </button>
        <button onClick={this.handleReset}>Reset</button>
      </div>
    </div>
  );
}












No comments:

Post a Comment