Build React Apps | Create a Clock Timer Using React 05

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Overview

After learning the basics of React and How it works under the hood from components to props and state management, in this tutorial we are going to apply our knowledge in order to create a clock Timer (Stop Watch) where you have the ability to start the timer, stop it or capture a certain time stamp (for ex: you are running), if we would use Vanilla JS (Native) this would be a little be complicated for us to make but React makes it super simple and Enjoyable to create so without further a do all you need is what you have learned and Vs Code (Code Editor) and time ti complete the timer, let's start.

Creating the Interface

First, we need to design our interface in order to add logic to it, so I have a full CSS premade for the seek of this tutorial if you want to have the same styling or you can use your custom Styling, you can grab the style and take a look on the final project on Github REPO, let's start by creating a Layout component that is going to be the main component (Also we are going to use only one component)

//Main Layout Component 
class Layout extends React.Component {
  constructor(props) {
     super(props);
  }

  render(props) {

  }
}

Now let's start by creating our App Layout, we are going to use the help of Bootstrap for easily getting container aligned up correctly alongside our Premade CSS (Take A Look at the Video For More Info).

...
render() {
   return (
    <div className="container">
      <h2 className="text-center">React Based Timer</h2>
      <div className="timer-container">
        <div className="current-timer">
        </div>
        <div className="timer-controls">
          <button className="btn btn-success">Start 
           Timer</button>
          <button className="btn btn-alert">Stop 
           Timer</button>
          <button className="btn btn-info">Capture Time</button>
          <button className="btn btn-danger">Reset!</button>
        </div>
      </div>
    </div>
);
}

So first we use the bootstrap container as Root Container then we create a current timer container that is going to holds the timer Clock and a timer Controls a bunch of controls buttons (Start, Stop, Reset...) very simple actually (Also the Styling is that perfect but does the job very perfectly).

Add Timer Logic

Now after finishing the setup of the clock and button controls interface it is time to add functionality to those buttons, starting, stopping and resting Timer alongside Capturing Different Timestamps.

First, Let's handle Timer Starting and the Displaying of the Hours. Minutes and Seconds Elapsed, so always make sure to store the data which is capable of change during the rendering process of your app under the state Object since react gonna optimize and rerender the component depending on the change of the current State.

constructor(props) {
  super(props);
  this.state = {
      timerStarted: false,
      timerStopped: true,
      hours: 0,
      minutes: 0,
      seconds: 0,
      captures: []
  }
  //We store the Timer Started and Stoped bool also the cptures array for rendering it on the app.
}

Beside different time stamps, we need to store if the timer is Started or Stopped as Boolean also the Captured Time in an Array so we define an empty array, now let's render the timer under the current timer container 

render() {
 ...
   <div className="current-timer">
     {this.state.hours + ":" + this.state.minutes + ":" + this.state.seconds}
   </div>
 ...
}

We show time as Hours:Minutes:Seconds Format (12:00:00), So let's Add Starting Timer Functionality 

...
handleTimerStart(e) {
  e.preventDefault();
  if(this.state.timerStopped) {
    this.timer = setInterval(() => {
        this.setState({timerStarted: true, timerStopped: false});
        if(this.state.timerStarted) {
          if(this.state.seconds >= 60) {
            this.setState((prevState) => ({ minutes: prevState.minutes + 1, seconds: 0}));
          }
          if(this.state.minutes >= 60) {
            this.setState((prevState) => ({ hours: prevState.hours + 1, minutes: 0, seconds: 0}));

          }
          this.setState((prevState) => ({ seconds: prevState.seconds + 1 }));
        }

    }, 1000);
  }
}

render() {
  ...
  <button className="btn btn-success" onClick={this.handleTimerStart.bind(this)}>Start 
  Timer</button>
  ...
}

First, we are checking the timer stopped so we can start it then using the setInterval we add one (1) each second (1000ms) to the seconds under the state object, after reaching 60 seconds we need to check if the Seconds are greater than 60 then it's a minute and the same for hours.

The SetInterval function takes a callback an execute it each certain number of milliseconds and we are repeating that every second so it gets updated.

Now you can check that by opening it in your browser and pressing the start button, the timer should start counting for you.

Let's add the ability to stop the timer.

So stopping the timer is actually very simple our case since we are triggering if the timer started or stopped, all we need to is change the state of our timer from started to stopped and the timer counting will stop because we are checking for that before setting the interval as well as we need to clear the interval.

...
handleTimerStop() {
  this.setState({timerStarted: false, timerStopped: true});
  clearInterval(this.timer);
}
...

Also, make sure to add the event listener on the click of the stop timer button 

render() {
  ...
  <button className="btn btn-alert" onClick={this.handleTimerStop.bind(this)}>Stop Timer</button>
  ...
}

And this all we need to do, now save refresh the page you should be able to stop the timer now on a specific time stamp, Awesome!

What's Next

That was all for this tutorial Part 01 in the next part we will handle time capturing and resetting for our timer App, Stay Tooned!

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games