Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access static properties of a component imported using React.lazy

i have a react functional component in a file like this -

const Slot: React.ElementType = () => null;
const Component = ({ children }): JSX.Element | null => {
  const childrenArr = React.Children.toArray(children) as React.ReactElement[];
  const slot = childrenArr.find(child => child.type === Slot);

  return (
    <div>
      <div>Hi</div>
      {slot && slot.props.children}
    </div>
  );
};

Component.Slot = Slot;
export default Component;

And i am using this compont by importing it in another using React.lazy

const Comp = React.lazy(() => import(/* webpackChunkName: "comp" */ './Component'))

I am rendering this component under React.Suspense, like this

 <Suspense fallback={null}>
   <Comp>
     Welcome
     <Comp.Slot>Robert</Comp.Slot>
   </Comp>
 </Suspense>

But Robert is not rendering. Also, i am getting Typescript error for Comp.Slot, saying

Property 'Slot' does not exist on type 'LazyExoticComponent<{ (): Element | null; Slot: FunctionComponent<any>;}>'.

What will be the best way to fix this? Please help.

like image 615
ghostCoder Avatar asked Oct 24 '25 02:10

ghostCoder


1 Answers

I believe lazy only works with default export and only with exact component being exported as it creates some sort of HOC around it.

What you can do is make this part

   <Comp>
     Welcome
     <Comp.Slot>Robert</Comp.Slot>
   </Comp>

standalone component and use lazy on it.

like image 60
Danila Avatar answered Oct 25 '25 16:10

Danila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!