0

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

ololo
  • 1,326
  • 2
  • 14
  • 47
  • Whats the reasoning behind lazy mounting instead of the normal conditional rendering. You should try conditional rendering instead. – Dennis Vash Dec 12 '21 at 11:59
  • Conditional rendering requires alot of code. I'm after efficient and minimal lines of code – ololo Dec 12 '21 at 12:01

1 Answers1

0

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>
    </>
  );
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118