1

I try to load dynamically in my dashboard using React.lazy() and Suspense component. It works really well with an hardcoded value, but not with a variable. I'm a little bit speechless right now. Probably a dumb error!

Works:

const WidgetComponent = React.lazy(() => import('../../../widgets/dummy/Dummy'));

Don't works:

// widget.path === '../../../widgets/dummy/Dummy'
const WidgetComponent = React.lazy(() => import(widget.path));

Don't works also:

const WidgetComponent = React.lazy(() => import(`${widget.path}`));

One thing I can add is the widget prop is filled from a json file in public folder.

Jonathan Anctil
  • 1,025
  • 3
  • 20
  • 44
  • 1
    Using variable would not work. Using an expression should work. [Answer to a similar problem](https://stackoverflow.com/a/62095265/2873538). [Another one](https://stackoverflow.com/a/62192731/2873538). But I think it is better to write: `React.lazy(() => import('../../../widgets/dummy/Dummy'));`. – Ajeet Shah Dec 24 '20 at 16:32
  • try \`${widget.path}\` instead of widget.path – ARZMI Imad Dec 24 '20 at 16:36
  • Works: import(`../../../widgets/${widget.component}`)); Don't works: import(`${widget.path}`)); – Jonathan Anctil Dec 24 '20 at 16:37
  • \`${widget.path}\` works, check it here https://codesandbox.io/s/reactlazy-forked-1yq4i?file=/src/index.js:259-265 – ARZMI Imad Dec 24 '20 at 16:50
  • @ARZMIImad ok I will retry, maybe the compiler who's messing with me... – Jonathan Anctil Dec 24 '20 at 16:59

1 Answers1

1

Ok, with the help of @Ajeet Shah I've solved my problem.

I've created a new property with the component name instead and I did that :

const WidgetComponent = React.lazy(() => import(`../../../widgets/${widget.component}`));

Not the most elegant solution, but it works.

Jonathan Anctil
  • 1,025
  • 3
  • 20
  • 44