Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React.lazy with TypeScript

Tags:

I am trying to use React.lazy for code splitting in my TypeScript React app.

All I am doing is changing that line:

import {ScreensProductList} from "./screens/Products/List"; 

to this line:

const ScreensProductList = lazy(() => import('./screens/Products/List')); 

But the import('./screens/Products/List') part triggers a TypeScript error, stating:

Type error: Type 'Promise<typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.   Property 'default' is missing in type 'typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")' but required in type '{ default: ComponentType<any>; }'. 

I am not quite sure what I am supposed to do here to get it to work.

like image 521
Johannes Klauß Avatar asked Jan 11 '19 16:01

Johannes Klauß


People also ask

Can you use React and TypeScript together?

If you'd rather use Create React App to initiate your project, you'll be pleased to know that CRA now supports TypeScript out of the box.

Should I use React lazy?

This is because the component will only be loaded when it is needed, and it will only be loaded once. So you should only use React. lazy when you need to load a component asynchronously. The component is not readily needed in the initial render of the app, and it is not needed in the render of a specific page.

Is lazy loading is possible in React?

It has been available for quite some time. In essence, lazy loading means that a component or a part of code must get loaded when it is required. It is also referred to as code splitting and data fetching . Talking about React specifically, it bundles the complete code and deploys all of it at the same time.

How do you use lazy load in React?

const OtherComponent = React.lazy(() => import('./OtherComponent')); This will automatically load the bundle containing the OtherComponent when this component is first rendered. React.lazy takes a function that must call a dynamic import() .


1 Answers

You should do export default class {...} from the ./screens/Products/list instead of export class ScreensProductList {...}.

Or, alternatively, you can do:

const ScreensProductList = lazy(() =>   import('./screens/Products/List')     .then(({ ScreensProductList }) => ({ default: ScreensProductList })), ); 
like image 92
Denis Zhbankov Avatar answered Jan 27 '23 08:01

Denis Zhbankov