0

`Here is my attempt to dynamically load a component at the click of a button, and show on page. https://codesandbox.io/s/sweet-haze-knste?file=/src/App.tsx

I am using the below line of code to dynamically import the component when button is clicked.

const importedComponent = React.lazy(() => import("./DynamicallyImportedComponent"));

And the state is set using

this.setState({
      importModule: importedComponent
      // importModule: CommonEditorCallout
    });

However, this does not render correctly.

When I use the regular import using the below, it renders fine

import DynamicallyImportedComponent from "./DynamicallyImportedComponent";

Is this possibly due to the fact that in the regular import I specify the name of the component I am importing, or something to do with the dynamic import itself?

1 Answer 1

0

Docs

The lazy component should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.

So wrapping your lazy loaded component with React.Suspense with a fallback props will fix the error.

 <React.Suspense fallback={<div>Loading...</div>}>
   {this.state.showImportedModule && <div>{<ComponentToShow />}</div>}
 </React.Suspense>

See example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.