I’m trying to do some animations in our React site. Since we can’t use normal DOM methods like getElementByID, I’m trying to access elements with useRef(), which is recommended by a lot of people. But I can’t get useRef() to grab anything.
const product2 = useRef(null);
useEffect(() => {
console.log('LOGGING REFS', product2.current);
}, [product2]);
return (
<div className='mb-[40px]' ref={product2}>
<h6 className='font-semibold'>Product 2</h6>
</div>
In the snippet above, the useEffect never fires and nothing is logged to the console. If I try and do something with product2.current in a useEffect, it throws an error because product2 is still null.
>Solution :
There doesn’t seem to be anything wrong in the provided code, here’s my reproduction and the "LOGGING REFS" is logging correctly.
Few things you could consider –
- Are you exporting and rendering this component correctly? This isn’t obvious from the code provided, add some logs at the top of the component to ensure the component is rendering correctly
Regarding your point "If I try and do something with product2.current in a useEffect, it throws an error because product2 is still null".
You would need to add a check for null in your useEffect before accessing the current property, see the updated useEffect below
useEffect(() => {
console.log('LOGGING REFS', product2.current);
if (product2) {
// do something
}
}, [product2]);