There is a functional component implemented with getElementById and it needs to be updated to use useRef hook.
Original code:
import React, { useState, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
const MyComponent: React.FunctionComponent<MyComponentProps> = ({
myDefaultElement = 'default-element',
}) => {
const [elementOutlet, setElementOutlet] = useState<HTMLOListElement>();
useEffect(() => {
const refElement = document.getElementById(myDefaultElement) as HTMLOListElement;
if (refElement) {
setElementOutlet(refElement);
}
}, [myDefaultElement]);
return createPortal(
<li>
// something
</li>,
elementOutlet
);
};
the above code works fine, the only change that I made was the first line inside useEffect.
From:
const refElement = document.getElementById(myDefaultElement) as HTMLOListElement;
To:
const refElement = useRef(myDefaultElement) as HTMLOListElement;
When hover the new line it says:
React Hook "useRef" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
Is there a way to make ref work fine inside useEffect?