You are currently viewing Making Analog Clock in React

Making Analog Clock in React

In this blog we will make analog clock in Reactjs from Scratch without using external Libraray

import React, { useState, useEffect } from "react";
import "./styles.css"; // Import CSS file for styles

const App = () => {
  const [hour, setHour] = useState(new Date().getHours() % 12);
  const [minute, setMinute] = useState(new Date().getMinutes());
  const [second, setSecond] = useState(new Date().getSeconds());

  useEffect(() => {
    // Update clock hands every second
    const timer = setInterval(() => {
      setHour(new Date().getHours() % 12);
      setMinute(new Date().getMinutes());
      setSecond(new Date().getSeconds());
    }, 1000);

    return () => {
      // Clean up timer when component is unmounted
      clearInterval(timer);
    };
  }, []);

  // Calculate rotation angles for clock hands
  const hourRotation = ((hour + minute / 60) * 360) / 12;
  const minuteRotation = ((minute + second / 60) * 360) / 60;
  const secondRotation = (second / 60) * 360;

  return (
    <>
      <h1 className="title">Mourya Works</h1>
      <div className="clockContainer">
        {/* {hour}:{minute}:{second} */}

        <div
          className="hour"
          style={{ transform: `rotate(${hourRotation}deg)` }}
        ></div>
        <div
          className="minute"
          style={{ transform: `rotate(${minuteRotation}deg)` }}
        ></div>
        <div
          className="second"
          style={{ transform: `rotate(${secondRotation}deg)` }}
        ></div>
      </div>
    </>
  );
};

export default App;
@import url("https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;700&display=swap");
h1 {
  font-family: "Poppins", sans-serif;
  text-align: center; /* Center aligns the text horizontally */
  display: flex; /* Enables flexbox layout for centering vertically */
  justify-content: center; /* Center aligns the text vertically */
}

.clockContainer {
  position: relative;
  margin: auto;
  height: 40vw;
  /*to make the height and width responsive*/
  width: 40vw;
  border-radius: 50%; /* set border-radius to 50% for a circle */
  border: 3px solid black; /* set border style, width, and color */
  /*setting our background image*/
}

.hour,
.minute,
.second {
  position: absolute;
  background: black;
  border-radius: 10px;
  transform-origin: bottom;
}

.hour {
  width: 1.8%;
  height: 25%;
  top: 25%;
  left: 48.85%;
  opacity: 0.8;
}

.minute {
  width: 1.6%;
  height: 30%;
  top: 19%;
  left: 48.9%;
  opacity: 0.8;
}

.second {
  width: 1%;
  height: 40%;
  top: 9%;
  left: 49.25%;
  opacity: 0.8;
}

Leave a Reply