Home > Blockchain >  LAZY LOADING "NAMESPACE" COMPONENT IN REACTJS
LAZY LOADING "NAMESPACE" COMPONENT IN REACTJS

Time:08-24

I'm try to write a namespace component in ReactJS. It has some problem that when i import a component "Menu" as lazy loading ( Menu already contain a component "Item" ) => when i used "Menu.Item" typescript will ping an error that ""Item" not exist in LazyExoticComponent<{}>". Anyone can help me please :(

Here is an example of me on codesandbox: https://codesandbox.io/s/keen-estrela-y63hyp?file=/src/App.tsx

***Menu.tsx

const MenuItem = ({ name }: { name: string }) => {
  return <p>{name}</p>;
};
const Menu = ({ children }: any) => {
  return <div>{children}</div>;
};
Menu.Item = MenuItem;
export default Menu;

***App.tsx

import { lazy } from "react";
import "./styles.css";
// good
// import Menu from "./components/menu";
// not good
const Menu = lazy(() => import("./components/menu"));
// Menu.Item not working when using lazy load...
export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Menu>
        this is error is below
        <Menu.Item name="element 1" />
        <Menu.Item name="element 2" />
        <Menu.Item name="element 3" />
      </Menu>
    </div>
  );
}

CodePudding user response:

you have to separate the menu and menuItem scripts, with the Lazy you can't export several components you have to do it one by one, you can't apply destructuring. If you want to have everything in one file and apply shredding you need to implement a library --> https://www.npmjs.com/package/react-lazily

now for now this work:

import { lazy } from "react";
import "./styles.css";
// good
// import Menu from "./components/menu";
// not good
const Menu = lazy(() => import("./components/menu"));
const MenuItem = lazy(() => import("./components/menuItem"));
// Menu.Item not working when using lazy load...
console.log(Menu);
export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Menu>
        <MenuItem name="element 1" />
        <MenuItem name="element 2" />
        <MenuItem name="element 3" />
      </Menu>
    </div>
  );
}

menu:

const Menu = ({ children }: any) => {
  return <div>{children}</div>;
};

export default Menu;

menuitem

const MenuItem = ({ name }: { name: string }) => {
  return <p>{name}</p>;
};
export default MenuItem;
  • Related