You can create a React component for an SVG clock with the useEffect
hook that updates the clock every second like this:
1706 chars41 lines
In this example, the Clock
component takes two props: size
and color
. The size
prop specifies the width and height of the SVG clock, while the color
prop specifies the color of the clock hands and the center dot.
The useEffect
hook is used to update the time
state every second by setting up an interval to call setTime
with the current date. The interval is cleared when the component unmounts using the function returned from the useEffect
hook.
The current time is then used to calculate the angles for the clock hands based on the current second, minute, and hour. These angles are then used to draw lines and a circle on the SVG element.
Note that the math for calculating the angles is done using radians, so the angles are converted from degrees to radians using (Math.PI / 180)
.
You can now use the Clock
component in your app like this:
154 chars9 lines
This will render a red SVG clock with a size of 200x200
in your app.
gistlibby LogSnag