How to pass refs to lazy load components
Unanswered
English Angora posted this in #help-forum
English AngoraOP
Hello guys I'm trying to pass refs to lazy load component but getting null instead of {current: null} please check where I'm doing mistake.
'use client';
import dynamic from 'next/dynamic';
import { useRef } from 'react';
const Component = dynamic(() => import('../components/Component'), {
ssr: false,
});
export default function Home() {
const ref = useRef(null);
return <Component ref={ref} />;
}
-------------------------------------------------------------------------
import { forwardRef, useEffect } from 'react';
const Component = forwardRef((props, ref) => {
useEffect(() => {
console.log(ref);
}, []);
return <h1>Practice</h1>;
});
export default Component;
'use client';
import dynamic from 'next/dynamic';
import { useRef } from 'react';
const Component = dynamic(() => import('../components/Component'), {
ssr: false,
});
export default function Home() {
const ref = useRef(null);
return <Component ref={ref} />;
}
-------------------------------------------------------------------------
import { forwardRef, useEffect } from 'react';
const Component = forwardRef((props, ref) => {
useEffect(() => {
console.log(ref);
}, []);
return <h1>Practice</h1>;
});
export default Component;
5 Replies
@English Angora Hello guys I'm trying to pass refs to lazy load component but getting null instead of {current: null} please check where I'm doing mistake.
'use client';
import dynamic from 'next/dynamic';
import { useRef } from 'react';
const Component = dynamic(() => import('../components/Component'), {
ssr: false,
});
export default function Home() {
const ref = useRef(null);
return <Component ref={ref} />;
}
-------------------------------------------------------------------------
import { forwardRef, useEffect } from 'react';
const Component = forwardRef((props, ref) => {
useEffect(() => {
console.log(ref);
}, []);
return <h1>Practice</h1>;
});
export default Component;
Cant remember correctly but ig the ref is going to be null initially. It should fill up correctly after the component loads(on CSR)
Use a useEffect hook and read the ref inside or something
Oh this doc is quite good now:
https://react.dev/reference/react/useRef
https://react.dev/reference/react/useRef
English AngoraOP
I read the docs but didn’t find solution
Did you use useEffect?