This is a Lazy Route component I wrote a while ago (code below).
This is what it does:
- It initially render a
lazyLoading = true
state to show some spinner or something. - Then on
useEffect
it will dynamic import() a component module and set theLazyComponent
state. LikesetLazyComponent(module)
- Then it will turn the loading to false and render
<LazyComponent.default />
Note: It works as intended.
My question is:
I've tried to do the following:
- Set the
default
property to the state. As insetLazyComponent(module.default)
. SinceSomeComponent
, which is the component that is being lazy loaded has a singledefault
export. - Then I should be able to render just
<LazyComponent/>
instead of<LazyComponent.default/>
- But it does not work.
And I get this error:
Why does it not work? All the rest of the code is the same. The only change I'm trying to make is the place where I access the default
property.
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
const LS = {};
LS.Container_DIV = styled.div`
`;
async function lazyRender() {
const module = await import("./SomeComponent");
return new Promise((resolve) => {
resolve(module);
});
}
function LazyRoute(props) {
console.log('Rendering LazyRoute...');
const [lazyLoading,setLazyLoading] = useState(true);
const [LazyComponent,setLazyComponent] = useState(null);
useEffect(() => {
async function getLazyComponent() {
const module = await lazyRender();
setLazyComponent(module);
setLazyLoading(false);
}
getLazyComponent();
},[]);
return(
lazyLoading ?
<div>I am Lazy Loading....</div>
: <LazyComponent.default {...props}/>
);
}
export default React.memo(LazyRoute);