Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef not grabbing DOM elements

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading