I'm trying a very simple test to understand component references in Next.js, but no matter what I do, current is always undefined.
Here's the setup (on a blank Next.js application): components/test.tsx
import {MouseEventHandler, ReactNode, RefAttributes} from "react";
interface TestProps {
onClick?: MouseEventHandler
}
export default function TestComp({ ...props }:TestProps & RefAttributes<unknown>) {
return (
<div onClick={props.onClick?props.onClick:undefined}>Test</div>
)
}
And then we have pages/index.tsx
import React, {createRef, forwardRef, useRef} from "react";
import TestComp from "../components/test";
// eslint-disable-next-line react/display-name
const TestWrapper = forwardRef((props: any, myref) => (
<TestComp{...props} ref={myref} />
));
const Home: NextPage = () => {
const el = useRef(null);
function testRef() {
console.log(el.current);
}
return (
<TestWrapper
myref={el}
onClick={testRef}
/>
);
};
Tried with useRef, createRef - nothing seems to work. el.current is always null or undefined. What am I doing wrong?
Thanks!
(This is with "next": "12.1.6", "react": "18.2.0", "react-dom": "18.2.0", FWIW )
Update Replacing "myref" with "ref" doesn't work either (complains that functional components can't have references)