I am trying to use a ref from a parent component to listen to certain ref events in the child component where the ref is attached to the child component using React.forwardRef. However, I am getting a linting complaint in my child component when I reference ref.current, stating:
Property 'current' does not exist on type 'Ref'. Property 'current' does not exist on type '(instance: HTMLDivElement) => void'
How am I supposed to reference a ref in a React.forwardRef component? Thanks.
index.tsx:
import * as React from "react";
import ReactDOM from "react-dom";
const Component = React.forwardRef<HTMLDivElement>((props, ref) => {
React.useEffect(() => {
const node = ref.current;
const listen = (): void => console.log("foo");
if (node) {
node.addEventListener("mouseover", listen);
}
return () => {
node.removeEventListener("mouseover", listen);
};
}, [ref]);
return <div ref={ref}>Hello World</div>;
});
export default Component;
const App: React.FC = () => {
const sampleRef = React.useRef<HTMLDivElement>(null);
return <Component ref={sampleRef} />;
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);