DEV Community

Cover image for Build a digital clock with React JS; A step-by-step guide
Kemi Owoyele
Kemi Owoyele

Posted on

Build a digital clock with React JS; A step-by-step guide

In this series of building simple projects with react, we are at the digital clock bus stop. Our final project will look like this;

Image description
Simply cool right?
So let’s get started by creating a react app. If you are not sure if you have the modern version of node in your computer, confirm by typing node –v in your terminal. If a version number does not show up, or the version is less than version 5.2, visit nodejs.org and download the latest version of node.
If you’ve done this, still in your terminal, navigate to the location you would like to create your app in and type in

  npx create-react-app digital-clock
Enter fullscreen mode Exit fullscreen mode

This may take a while, as npx runs the code on the internet and downloads a new app for you along with all the needed dependencies for a starter project. After the app is created, navigate into the app and type code. To open the code in vscode(if that is your default code editor). If your default code editor is not vscode, open up your editor to the newly created folder. To run the app on the browser, type npm start in the terminal. Ensure that the terminal is addressed to the root folder.

Create the DigitalClock component

In the src folder of the app created for you, create a new file and name it DigitalClock.js. In the file, create a basic react component and export it at the bottom.

const DigitalClock = () => {
  return <></>;
};
export default DigitalClock;

Enter fullscreen mode Exit fullscreen mode

Now, go to the root component of your app and replace the content with the codes below

import DigitalClock from "./DigitalClock";
function App() {
  return (
    <>
  <DigitalClock />
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

This is to import the DigitalClock component into the App component and render the DigitalClock.

Write the relevant jsx and CSS

In our DigitalClock component, we will render our jsx codes for displaying the time in hours, minutes and seconds. We will also display the date in another section of the clock.

const DigitalClock =() => {
  return (
    <>
      <div className="clock-container">
        <div className="cover"></div>
        <p className="date">sun 1 Jan 2020</p>
        <div className="time">
          <span className="clock">00:</span>
          <span className="clock">00:</span>
          <span className="secs">00</span>
        </div>
        <p className="date">00:00:00 am</p>
      </div>
    </>
  );
}
export default DigitalClock;


Enter fullscreen mode Exit fullscreen mode

Paste the following CSS style in your index.css file to replace the former content of the file.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  margin: 0;
  font-family: "Segoe UI", "Roboto", sans-serif;
  background: black;
  background: linear-gradient(
      45deg,
      rgb(184, 183, 185),
      rgb(90, 89, 133),
      rgb(158, 158, 161)
    ),
    conic-gradient(
      rgba(148, 195, 240, 0.4),
      rgba(107, 111, 131, 0.4),
      rgba(225, 192, 255, 0.4),
      rgba(82, 105, 184, 0.4)
    );
  background-size: 20px 50px, 100px 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  color: rgb(18, 17, 68);
  text-shadow: 1px 1px 2px rgb(255, 255, 255);
  -webkit-text-stroke: 1px rgb(0, 0, 0);
  font-family: monospace;
  background-blend-mode: color-burn;
}
.clock-container {
  padding: 20px;
  border-radius: 50%;
  background-color: rgb(125, 130, 148);
  background-size: 3px 5px;
  box-shadow: inset 5px 5px 5px rgb(0, 0, 0), inset -5px -5px 5px rgb(0, 0, 0);
  height: 250px;
  width: 250px;
  position: relative;
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  align-items: center;
  text-align: center;
}
.cover {
  position: absolute;
  top: 5%;
  left: 5%;
  width: 90%;
  height: 90%;
  box-shadow: inset 5px 5px rgb(5, 5, 5), inset -5px -5px rgb(5, 5, 5);
  background-color: rgba(0, 2, 10, 0.363);
  background: conic-gradient(
    rgb(185, 185, 199),
    rgb(205, 205, 243),
    rgb(139, 147, 177),
    rgb(139, 141, 175)
  );
  opacity: 0.3;
  border-radius: 50%;
}
.date {
  font-size: 1rem;
  font-weight: 900;
}

.time {
  padding: 10px 0;
  border-radius: 30px;
  background: rgb(0, 0, 69);
  color: #fff;
  font-size: 2rem;
  font-weight: 900;
  text-shadow: 1px 1px 2px rgb(91, 109, 161);
  -webkit-text-stroke: 1px rgb(0, 0, 0);
  box-shadow: 3px 5px 5px rgb(5, 5, 5);
}
.secs {
  font-size: 1rem;
}

Enter fullscreen mode Exit fullscreen mode

Outcome so far

Image description

Write the code for getting the time

So now we have a clock, but it’s not yet working. To make the clock work we will need to import two hooks. These are the useState hook and the useEffect hook.

import { useState, useEffect } from "react";
Enter fullscreen mode Exit fullscreen mode

_The useState hook is used render variable updates, or variable state changes to the DOM. While useEffect hook is used to handle function side effects. _

To use the useState hook, we assign useState to a variable and a function for setting the value of the time variable. And give it an initial value of the new date object.

  const [time, setTime] = useState(new Date());
Enter fullscreen mode Exit fullscreen mode

get the time to start running

To get the time to update every second, we will have to run the update every second with the JavaScript setInterval method. And in react, actions like setting timers, fetching API, localstorage and other side effect producing functions are usually taken care of with the useEffect hook. This is also useful for cleaning up resources that are no longer in use with the cleanup function. Hence, inside the useEffect function, we will run the setInterval function, and return the cleanup function.

  useEffect(() => {
    const timeInterval = setInterval(() => {
      setTime(new Date());
    }, 1000);

    return () => clearInterval(timeInterval);
  }, []);

Enter fullscreen mode Exit fullscreen mode

Display the time on the clock

Now we have the clock and the running time. But the time is yet to be displayed on the clock. So to display the time, we use curly braces to embed time. But we want to output date in one div, output the time in 12 hour format in another div and output the hours, minutes and seconds in another div. we will attach to the time variable the different relevant functions to extract the particular version of the time we need.

<p className="date">{time.toDateString()}</p>
        <div className="time">
          <span className="clock">{time.getHours()}:</span>
          <span className="clock">{time.getMinutes()}:</span>
          <span className="secs">{time.getSeconds()}</span>
        </div>
        <p className="date">{time.toLocaleTimeString()}</p>


Enter fullscreen mode Exit fullscreen mode

The overall code for the DigitalClock component will be as below.

import { useState, useEffect } from "react";

function DigitalClock() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const timeInterval = setInterval(() => {
      setTime(new Date());
    }, 1000);

    return () => clearInterval(timeInterval);
  }, []);
  return (
    <>
      <div className="clock-container">
        <div className="cover"></div>
        <p className="date">{time.toDateString()}</p>
        <div className="time">
          <span className="clock">{time.getHours()}:</span>
          <span className="clock">{time.getMinutes()}:</span>
          <span className="secs">{time.getSeconds()}</span>
        </div>
        <p className="date">{time.toLocaleTimeString()}</p>
      </div>
    </>
  );
}
export default DigitalClock;


Enter fullscreen mode Exit fullscreen mode

Final Result

Image description

Conclusion

We now have a functional digital clock that we built together with React. I will recommend that you try to build this app again on your own. You can make adjustments to the app if you deem fit. Also, try to build other simple projects to help you get more comfortable with React JS.
Let me know your outcomes, and whatever challenges you may face in the comment section. Also, if you want to read more front-end web development content, follow this account. Thank you.

Top comments (0)