Trying to use useRef hook on a functional component. I’m getting: {current: null} when I try to log this to console. Any thing look off here?
import React, {useRef} from 'react';
const Hi = () => (
const span = useRef<HTMLSpanElement>(null);
console.log(span);
return(
<div>
<p>hi</p>
</div>
)
);
export default Hi;
2
Answers
useRef
doesn’t create an HTML element; rather, you need to attach the resulting reference to an appropriate JSX element (by writing e.g.<span ref={span} />
), and React will then update the reference to point to the relevant element node or component.This means two things:
For more information, see https://react.dev/reference/react/useRef#manipulating-the-dom-with-a-ref