I'm trying to use React.lazy to lazy load a React Component. The component looks like this:
function App() {
const HubScreen = React.lazy(() => import("./screens/hub").then((mod) => {
console.log(mod.default)
return mod.default;
}));
return (
<BrowserRouter>
<MuiThemeProvider theme={theme}>
<MainContaier>
<div id="screen">
<CssBaseline />
<Switch>
<React.Suspense fallback={<h1>Loading...</h1>}>
<Route exact path="/" component={HomeScreen} />
<Route path="/hub" render={() => <HubScreen />} />
</React.Suspense>
</Switch>
</div>
</MainContaier>
</MuiThemeProvider>
</BrowserRouter >
)
}
And this is the component I'm importing
import React from "react";
function HubScreen() {
return (
<div>Hi</div>
);
}
export default HubScreen;
When I navigate to /hub
I see the value of mod.default
as undefined. Along with my Chrome window becoming completely unresponsive, requiring a force stop.
I know that my path to the module ./screens/hub
, is correct because, if I put a fake path like ./screens/hube
then webpack gives me the error:
Module not found: Error: Can't resolve './screens/hube' in '/home/travis/Workspace/avalon/assets/js'
I'm stumped haven't found a similar problem anywhere.
This answer gave me some insight as to why my browser was hanging up. However I still seem to have the same root problem; the undefined module.default. After changing the root component to this:
const HubScreen = React.lazy(() => import("./screens/hub"));
function App() {
return (
<BrowserRouter>
<MuiThemeProvider theme={theme}>
<MainContaier>
<div id="screen">
<CssBaseline />
<Switch>
<React.Suspense fallback={<h1>Loading...</h1>}>
<Route exact path="/" component={HomeScreen} />
<Route path="/hub" component={HubScreen} />
</React.Suspense>
</Switch>
</div>
</MainContaier>
</MuiThemeProvider>
</BrowserRouter >
)
}
I get the War:
Warning: lazy: Expected the result of a dynamic import() call. Instead received: [object Object]
Your code should look like:
const MyComponent = lazy(() => import('./MyComponent'))
And then the error:
Uncaught Error: Element type is invalid. Received a promise that resolves to: undefined. Promise elements must resolve to a class or function.
Which I have taken to mean that undefined is being returned from the import resolution, as the console.log seems to confirm.
Also another possibility of getting this error is by missing the default export in your Component which becomes a named export.
This syntax is only supported for Default exports.
const HubScreen = React.lazy(() => import("./screens/hub"));
import React, {useState} from 'react';
const ChangeName = (props) => {
return (
<div>
<p>Name: {props.name}</p>
<p>Email: {props.email}</p>
<div>
<button onClick={()=>props.changeStatus()}>Change Details</button>
</div>
</div>
)
}
export default ChangeName; ====> By missing the default Export
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With