How to use React useRef hook with typescript? How to use React useRef hook with typescript? reactjs reactjs

How to use React useRef hook with typescript?


anchorEl variable is ref object, an object that has only current property. It's unknown how Popover works but, but it expects an element as anchorEl prop, not a ref.

It should be:

<Popover    id="simple-popper"    open={open}    anchorEl={anchorEl.current}

If <Popover and <div ref={anchorEl} > are siblings like it's shown, a ref won't be ready to use at the moment when it's passed as a prop. In this case a component needs to be re-rendered on mount:

const [, forceUpdate] = useState(null);useEffect(() => {  forceUpdate({});}, []);...   { anchorEl.current && <Popover        id="simple-popper"        open={open}        anchorEl={anchorEl.current}        ...   }   <div ref={anchorEl} >

In case <div ref={anchorEl} > doesn't have to be rendered to DOM, it could be

   <Popover        id="simple-popper"        open={open}        anchorEl={<div/>}

The necessity to render a component twice and use forceUpdate workaround suggests that this could be done in a better way. The actual problem here is that Popover accepts an element as a prop, while accepting refs is common in React.

At this point ref object has no benefits. Ref callback can be used with useState instead, state update function is callback that receives new state as an argument and it doesn't cause additional updates if it receives the same state (DOM element):

const [anchorEl, setAnchorEl] = useState<HTMLDivElement>(null);...   { anchorEl && <Popover        id="simple-popper"        open={open}        anchorEl={anchorEl}        ...   }   <div ref={setAnchorEl} >