JillAndMe
JillAndMe

Reputation: 4551

React.lazy() with Typescript

I got the error :

Property 'default' is missing in type 'Element' but required in type '{ default: ComponentType; }'.ts(2322)

   {React.lazy(() => import(`../../i18n/locales/${this.props.lang}`).then(o => (
              <CustomSelects
                options={o.option}
                formattedMessageId="createroom_genre"
                value={this.props.genre}
                handleValueChange={this.handleGenreChange}
              />
            ))) }

I read Using React.lazy with TypeScript but, I don't know how to do this in my case.

Let me know if you need more info. Thanks.

Upvotes: 3

Views: 5113

Answers (1)

Estus Flask
Estus Flask

Reputation: 222503

Components shouldn't be declared in-place where they are used, this may kill optimizations and potentially result in infinite loop.

React.lazy is intended to be used with dynamic import, callback function is supposed to return a promise of a module, i.e. { default: Component } object, but it currently returns a promise of React element.

React.lazy wasn't intended to be parameterized, it doesn't accept props and this.props.lang can't work there. It should be wrapped with another component to receive props:

const LocalCustomSelects = React.memo(({ lang }) => {
  const Lazy = React.lazy(async () => {
    const o = await import(`../../i18n/locales/${lang}`);
    return { default: props => <CustomSelects ... /> };
  });

  return <Lazy/>;
});

Upvotes: 5

Related Questions