'Why does this simple React component throw an error when I try to run it?
This is a trivial analog clock that seems simple enough. However, it seems to fail at line 7 with "TypeError: Cannot read properties of null (reading 'style')". I've also tried the setAttribute() method and get the same thing. How do I dynamically update the rotation every second?
export const Analog = () => {
function setDate() {
let secondHand = document.querySelector(".second-hand");
const now = new Date();
const seconds = now.getSeconds();
const secondsDegrees = (seconds / 60) * 360 + 90;
secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
}
setInterval(setDate, 1000);
return (
<svg id="clock" className="min-w-full min-h-full" viewBox="0 0 100 100">
<circle id="face" cx="50" cy="50" r="50" />
<g id="hands">
<circle id="center" cx="50" cy="50" r="2" fill="white" />
<line
id="secondHand"
className="second-hand"
x1="50"
y1="50"
x2="50"
y2="0"
/>
</g>
</svg>
);
};
Solution 1:[1]
It could be timing issues between executing the setInterval and actual mounting of the component (<Analog />) itself. You should use componentDidMount in case of class components or you can use useEffect in case of functional component .
NOTE: Try not to bypass React in order to access DOM (like document.querySelector()).
Solution 2:[2]
Is there any other element using second-hand, I assume not? At each render, your function will run before the element is returned, hence your secondHand is undefined.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anant Sharma |
| Solution 2 | Hung Vu |
