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.

5
  • 1
    Using variable would not work. Using an expression should work. Answer to a similar problem. Another one. But I think it is better to write: React.lazy(() => import('../../../widgets/dummy/Dummy'));. Commented Dec 24, 2020 at 16:32
  • try `${widget.path}` instead of widget.path Commented Dec 24, 2020 at 16:36
  • Works: import(../../../widgets/${widget.component})); Don't works: import(${widget.path})); Commented Dec 24, 2020 at 16:37
  • `${widget.path}` works, check it here codesandbox.io/s/reactlazy-forked-1yq4i?file=/src/… Commented Dec 24, 2020 at 16:50
  • @ARZMIImad ok I will retry, maybe the compiler who's messing with me... Commented Dec 24, 2020 at 16:59

1 Answer 1

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.

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.