Ref always return null in Loadable Component

387 Views Asked by At

I am using this react library https://github.com/gregberge/loadable-components to load a Component with Ref to access instance values using useImperativeHandle but ref is always null.

Here is my code

import loadable from '@loadable/component';

export default function ParentComponent(props){

const currentPageRef = useRef();
const[currentPage,setCurrentPage]=useState();

  const loadPage= (page= 'home') => {
      const CurrentPage = loadable(() => import(`./${page}`));
      return (
          <CurrentPage 
              ref={currentPageRef}
           />
      );
  }

  useEffect(() => {
          console.log(currentPageRef); //This is always logging current(null);
          let pageTitle= currentPageRef.current?.getTitle();
          let pageSubTitle= currentPageRef.current?.getSubTitle();
          console.log(` Page Title=${pageTitle}`); //This is always coming back as null
          console.log(`Page SubTitle=${pageSubTitle}`); //This is also always coming back as null
  }, [currentPage]);

 return (
            <div>
                        <button onClick={() => {
                                        setCurrentPage(loadPage('youtube));
                                    }}>
                        LoadPage
                        </button>
            </div>
      );
}

Where each of the child components contains a useImperativeHandle to expose instance functions but I can't seem to access any of the functions because currentPageRef is always null

Here is an example of one of the child pages that contains the useImperativeHandle implementation


   const YouTubePage= React.forwardRef((props,ref)=>{

   const [connected, setConnected] = useState(false);

   const getTitle = () => {
        return connected ? "Your YouTube Channels" : "YouTube";
    }

    const getSubTitle = () => {
        return connected ? "Publishable content is pushed to only connected channels. You may connect or disconnect channel(s) as appropriate" : "Connect a YouTube account to start posting";
    }

    useImperativeHandle(ref, () => ({ getTitle, getSubTitle }));

    return (<div></div>);
});

Any ideas as to why that might be happening?

Thank you

1

There are 1 best solutions below

1
Dennis Vash On

From your code example your aren't actually rendering the component which you set by the state setter:

export default function ParentComponent(props) {
  //...

  // Render the page
  return (
    <>
      {currentPage}
      <div>...</div>
    </>
  );
}