react component of an svg clock that has a useeffect hook that updates the clock every second in typescript in javascript

Here's how you can create a clock component in React using SVG and TypeScript, with a useEffect hook that updates the clock every second.

import React, { useState, useEffect } from 'react';

interface ClockProps {
  size: number;
}

const Clock: React.FC<ClockProps> = ({ size }) => {
  const [time, setTime] = useState(new Date());

  // Update the clock every second
  useEffect(() => {
    const intervalID = setInterval(() => {
      setTime(new Date());
    }, 1000);

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

  // Calculate the position of the clock hands
  const seconds = time.getSeconds();
  const minutes = time.getMinutes();
  const hours = time.getHours() % 12;

  const secondsAngle = (seconds / 60) * 360;
  const minutesAngle = ((minutes + seconds / 60) / 60) * 360;
  const hoursAngle = ((hours + minutes / 60) / 12) * 360;

  return (
    <svg width={size} height={size} viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="48" fill="none" stroke="black" strokeWidth="2" />
      <line
        x1="50"
        y1="50"
        x2="50"
        y2="15"
        stroke="black"
        strokeWidth="2"
        transform={`rotate(${hoursAngle}, 50, 50)`}
      />
      <line
        x1="50"
        y1="50"
        x2="50"
        y2="10"
        stroke="black"
        strokeWidth="1"
        transform={`rotate(${minutesAngle}, 50, 50)`}
      />
      <line
        x1="50"
        y1="50"
        x2="50"
        y2="5"
        stroke="black"
        strokeWidth="1"
        transform={`rotate(${secondsAngle}, 50, 50)`}
      />
    </svg>
  );
};

export default Clock;
1467 chars
63 lines

This component takes in a size prop, which determines the width and height of the SVG element. The useEffect hook initializes an interval that updates the time state every second. The hours, minutes, and seconds variables are used to calculate the angle (in degrees) of the clock hands, which are then rotated using the transform attribute of the line elements within the SVG.

gistlibby LogSnag