skip to Main Content

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?

2

Answers


  1. 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"))
    
    Login or Signup to reply.
  2. You can avoid the intermediate module by doing this:

    const MyComponent = React.lazy(() =>
      import('./MyComponent').then((module) => ({ default: module.MyComponent }))
    );
    

    It’s annoying to type, so I’ve personally started to use react-lazily instead, which will reduce the above to

    const { MyComponent } = lazily(() => import('./MyComponent'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search