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;
I’m expecting {current: null} this output in Component
2
Answers
The issue you’re encountering arises because the
ref
is not being forwarded correctly to the lazy-loaded component. In React, when you useforwardRef
, the ref is correctly passed to the component, but with dynamic imports, it requires special handling.To ensure the ref is correctly forwarded, you can make the following adjustments:
forwardRef
and that the ref is being passed down properly:dynamic
from Next.js, you need to ensure that the dynamic import correctly handles the ref forwarding. To do this, use a wrapper to applyforwardRef
around the lazy-loaded component:In this setup, the ref should correctly pass through and be logged as
{ current: null }
when the component mounts.Home.js
Component.js
Server-Side Rendering: When using
ssr: false
, remember that the component is not rendered on the server side, so ref handling might be different compared to a standard render.Client-Side Only: Ensure that your code relying on
ref
is placed in a client-side hook likeuseEffect
to avoid issues related to server-side rendering.