Search code examples
reactjslazy-loading

How do I lazy-load an "import { SelectedComponent } from {Library}"?


I'm using React 18 with Vite and Ionic and I'm trying to lazy-load the IonDatetime component:

import { IonDatetime } from '@ionic/react';
const ControllerDatetime: React.FC<ControllerDatetimeProps> = ({
  control,
  label,
  name,
  clearErrors,
  disabled,
}: ControllerDatetimeProps) => {
  return (
    <Controller
      control={control}
      name={name}
      rules={{ required: true }}
      render={({
        field: { onChange, onBlur, value },
        fieldState: { invalid, isTouched },
      }) => (
        <IonDatetime>
          {label}
        </IonDatetime>
      )}
    />
  );
}

I can't figure out how to use lazy-loading here though.

I tried

const IonDatetime = React.lazy(() => import { IonDatetime } from '@ionic/react')

but it results in a syntax error.

I'm using lazy loading successfully to get default exports of my own components, but how do I lazy-load a specific component from a third-party library?


Solution

  • React.lazy currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused components. (Legacy React code-splitting docs)

    // IonDatetime.js
    export { IonDatetime as default } from "@ionic/react";
    
    const IonDatetime = React.lazy(() => import("IonDatetime.js"))