You are currently viewing Alarm Clock With React JS (Code + Demo)

Alarm Clock With React JS (Code + Demo)

In this tutorial, we will explore how to build an alarm clock in React. React is a popular JavaScript library for building user interfaces, and it provides a powerful and efficient way to create interactive web applications. 

By the end of this React JS Alarm Clock tutorial, you will have a fully functional alarm clock that can be customized and set to notify you at a specific time. Let’s get started!

In today’s fast-paced world, having a reliable react alarm clock is essential to help us start our day on time. While there are numerous alarm clock apps available, why not create your own customized alarm clock with React? React is a JavaScript library widely used for building user interfaces, and its component-based architecture makes it an excellent choice for creating interactive applications.

Alarm Clock in React JS

In this React Alarm Clock tutorial, we will walk through the process of building an alarm clock application using React. By the end of this tutorial, you will have a fully functional alarm clock that allows you to set alarms, customize alarm times, and receive notifications when the alarms go off.

See the Pen React Alarm by Shynaf (@shynaf) on CodePen.

Step 1: Creating the Alarm Clock Component

First create the React JS Alarm Clock component.

				
					<div id='myClock'></div>
				
			

Step 2: Design a React JS Alarm Clock

Now React JS Alarm Clock needs to be designed with CSS. Here is some basic css used. But you can change it according to your requirement.

				
					html {
  background: #202050;
  color: white;
}

.container {
  margin-top: 5%;
  text-align: center;
}

#main-card, #timer-card {
  background: #101020;
  padding-top: 3%;
  border: 3px solid teal;
  border-radius: 2%;
}

#time-left {
  font-size: 50px;
}

#break-length, #session-length {
  font-size: 25px;
}

.btn {
  margin: 2px;
}
				
			

Step 3: Alarm Clock's React JS

Now we need to use javascript to activate Alarm Clock React.

				
					import * as React from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";

//The code defines a class component called Clock that extends the React.Component base class. This class component represents the clock application.
class Clock extends React.Component {
//In the constructor, the initial state of the Clock component is defined using the this.state object. It contains properties such as brkVal (break duration), sesVal (session duration), min (current time), interv (interval ID), and lbl (label for the alarm).
  constructor(props) {
    super(props);
    this.state = {
      brkVal: 1,
      sesVal: 1,
      min: [25, 0],
      interv: '',
      lbl: 'Alarm' };

    this.klik = this.klik.bind(this);
    this.timer = this.timer.bind(this);
  }
  //The componentDidMount() method is a lifecycle method that is called after the component has been rendered to the DOM. In this code, it sets the initial values of brkVal and sesVal in the component's state to 5 and 25, respectively.
  componentDidMount() {
    this.setState({ brkVal: 5, sesVal: 25 });
  }
  //The timer() method is responsible for managing the clock functionality. It takes an optional parameter x, which determines the action to be performed (e.g., start, pause, stop). The method accesses the relevant values from the component's state, such as brkVal, sesVal, min, interv, and lbl.
  timer(x) {
    const { brkVal, sesVal, min, interv, lbl } = this.state;
    let m = min[0];
    let n = min[1];

    let lab = lbl;
    if (interv == '') {
      this.state.interv = setInterval(() => {
        if (n - 1 < 1 && m != 0) {
          this.setState({ min: [m - 1, 60] }),
          m = m - 1, n = 60;
        };
        if (m === 0 && n === 0 && lab === 'Alarm') {
          lab = 'snooz',
          document.getElementById('beep').play(),
          this.setState({ min: [brkVal, 0], lbl: lab }),
          m = brkVal, n = 0;
        };
        if (m === 0 && n === 0 && lab === 'snooz') {
          lab = 'Alarm',
          document.getElementById('beep').play(),
          this.setState({ min: [sesVal, 0], lbl: lab }),
          m = sesVal, n = 0;
        };
        if (n - 1 > 0) {n = n - 1;} else if (m - 1 < 0) {n = 0;};
        this.setState({ min: [m, n], lbl: lab });
      }, 1000);
    };
    if (x == 'pause') {
      clearInterval(this.state.interv);
      this.setState({ min: [m, n] });
    };
    if (x === 'stop') {
      clearInterval(this.state.interv);
    };

  }
  
  //The klik() method handles user interactions with the clock application. It takes a parameter x, which determines the action to be performed (e.g., increment, decrement, reset). The method accesses the relevant values from the component's state, such as brkVal, sesVal, and min.
  //The klik() method uses a switch statement to handle different actions. Based on the provided action, it updates the state values and performs additional operations like starting or stopping the timer.
  klik(x) {
    const { brkVal, sesVal, min } = this.state;
    switch (x) {
      case 'breakInc':
        return this.setState({ brkVal: brkVal + 1 > 60 ? 60 : brkVal + 1 });
      case 'breakDec':
        return this.setState({ brkVal: brkVal - 1 < 1 ? 1 : brkVal - 1 });
      case 'sessionInc':
        this.setState({ min: [min[0] + 1 > 60 ? 60 : min[0] + 1, min[1]] });
        return this.setState({ sesVal: sesVal + 1 > 60 ? 60 : sesVal + 1 });
      case 'sessionDec':
        this.setState({ min: [min[0] - 1 < 1 ? 1 : min[0] - 1, min[1]] });
        return this.setState({ sesVal: sesVal - 1 < 1 ? 1 : sesVal - 1 });
      case 'reset':
        this.timer('stop'),
        document.getElementById('beep').pause(),
        document.getElementById('beep').currentTime = 0;
        return this.setState({
          brkVal: 5,
          sesVal: 25,
          min: [25, 0],
          interv: '',
          lbl: 'Alarm' });

      default:
        return '';}

  }
  render() {
    console.log(this.state.min);
    return /*#__PURE__*/(
      React.createElement("div", { className: "container" }, /*#__PURE__*/
      React.createElement("div", { className: "row" }, /*#__PURE__*/
      React.createElement("audio", {
        src: "https://assets.mixkit.co/sfx/download/mixkit-video-game-bomb-alert-2803.wav",
        id: "beep" }), /*#__PURE__*/

      React.createElement("div", { className: "col s12 m12 l2", id: "gap" }), /*#__PURE__*/

      React.createElement("div", { className: "col s12 m12 l8 card z-depth-4", id: "main-card" }, /*#__PURE__*/
      React.createElement("div", { className: "row" }, /*#__PURE__*/
      React.createElement(Break, { valBreak: this.state.brkVal,
        incBreak: () => this.klik('breakInc'),
        decBreak: () => this.klik('breakDec') }), /*#__PURE__*/
      React.createElement(Session, { valSession: this.state.sesVal,
        incSession: () => this.klik('sessionInc'),
        decSession: () => this.klik('sessionDec') }), /*#__PURE__*/
      React.createElement(Timer, {
        lab: this.state.lbl,
        time: this.state.min,
        start: () => !this.state.interv ?
        this.timer() : (
        this.timer('stop'),
        this.state.interv = ''),
        res: () => this.klik('reset') }))), /*#__PURE__*/



      React.createElement("div", { className: "col s12 m12 l2", id: "gap" }))));



  }}
;

function Break(props) {
  return /*#__PURE__*/(
    React.createElement("div", { className: "col s12 m6 l6", id: "br" }, /*#__PURE__*/

    React.createElement("div", { className: "card-title", id: "break-label" }, "Snooz"), /*#__PURE__*/



    React.createElement("div", { className: "card-content row l12" }, /*#__PURE__*/

    React.createElement("div", { className: "col s4 m4 l4" }, /*#__PURE__*/
    React.createElement("a", { className: "btn-floating btn-small waves-effect waves-light pink",
      onClick: props.decBreak,
      id: "break-decrement" }, /*#__PURE__*/
    React.createElement("i", { className: "fas fa-angle-down" }))), /*#__PURE__*/



    React.createElement("p", { className: "col s4 m4 l4", id: "break-length" }, props.valBreak), /*#__PURE__*/

    React.createElement("div", { className: "col s4 m4 l4" }, /*#__PURE__*/
    React.createElement("a", { className: "btn-floating btn-small waves-effect waves-light cyan",
      onClick: props.incBreak,
      id: "break-increment" }, /*#__PURE__*/
    React.createElement("i", { className: "fas fa-angle-up" }))))));






};

function Session(props) {
  return /*#__PURE__*/(
    React.createElement("div", { className: "col s12 m6 l6", id: "ss" }, /*#__PURE__*/

    React.createElement("div", { className: "card-title", id: "session-label" }, "Set Alarm"), /*#__PURE__*/



    React.createElement("div", { className: "card-content row l12" }, /*#__PURE__*/
    React.createElement("div", { className: "col s4 m4 l4" }, /*#__PURE__*/
    React.createElement("a", { className: "btn-floating btn-small waves-effect waves-light pink",
      onClick: props.decSession,
      id: "session-decrement" }, /*#__PURE__*/
    React.createElement("i", { className: "fas fa-angle-down" }))), /*#__PURE__*/



    React.createElement("p", { className: "col s4 m4 l4", id: "session-length" },
    props.valSession), /*#__PURE__*/


    React.createElement("div", { className: "col s4 m4 l4" }, /*#__PURE__*/
    React.createElement("a", { className: "btn-floating btn-small waves-effect waves-light cyan",
      onClick: props.incSession,
      id: "session-increment" }, /*#__PURE__*/
    React.createElement("i", { className: "fas fa-angle-up" }))))));






}

function Timer(props) {

  return /*#__PURE__*/(
    React.createElement("div", { className: "row" }, /*#__PURE__*/
    React.createElement("div", { className: "col s1 m2 l2", id: "gap" }), /*#__PURE__*/

    React.createElement("div", { className: "card-content col s10 m8 l8" }, /*#__PURE__*/
    React.createElement("div", { className: "col s3", id: "gap" }), /*#__PURE__*/
    React.createElement("div", { className: "col s12 card-panel z-depth-2", id: "timer-card" }, /*#__PURE__*/
    React.createElement("div", { className: "card-title col s12", id: "timer-label" },
    props.lab), /*#__PURE__*/

    React.createElement("div", { id: "time-left" },

    props.time[0] ?
    props.time[0] < 10 && props.time[0] != 0 ?
    '0' + props.time[0] : props.time[0] :
    '0' + 0, ":",



    props.time[1] ?
    props.time[1] < 10 && props.time[1] != 0 ?
    '0' + props.time[1] : props.time[1] :
    '0' + 0)), /*#__PURE__*/



    React.createElement("div", { className: "col s3", id: "gap" }), /*#__PURE__*/
    React.createElement("div", { className: "row", id: "timer-btn" }, /*#__PURE__*/
    React.createElement("div", { className: "col s3", id: "gap" }), /*#__PURE__*/
    React.createElement("div", { className: "col s12", id: "btns" }, /*#__PURE__*/
    React.createElement("a", { className: "btn waves-effect waves-light cyan",
      id: "start_stop",
      onClick: props.start }, /*#__PURE__*/
    React.createElement("i", { className: "fas fa-play" }), /*#__PURE__*/
    React.createElement("i", { className: "fas fa-pause" })), /*#__PURE__*/

    React.createElement("a", { className: "btn waves-effect waves-light pink",
      onClick: props.res,
      id: "reset" }, /*#__PURE__*/
    React.createElement("i", { className: "fas fa-sync" }))), /*#__PURE__*/


    React.createElement("div", { className: "col s3", id: "gap" }))), /*#__PURE__*/



    React.createElement("div", { className: "col s1 m2 l2", id: "gap" })));


}
//The render() method is a required method in a React component that defines what should be rendered to the DOM.
ReactDOM.render( /*#__PURE__*/React.createElement(Clock, null), document.getElementById('myClock'));
				
			

Hopefully from this article you have learned how to create a React Alarm Clock. All the code to make this react alarm clock is in the download button below.