I get an array like
{Path:xxx,
Component:"./xxx/ComPXX"}
from my API and based on that create my application's routes. At the moment I'm using React-Loadable (5.5.0) and React-Router (4.4.0-betax to avoid warnings in strict mode). See working example here.
Since React 16.6 has introduced React.lazy, I'm trying to migrate my solution, however I'm facing errors and difficulties however I try to do this. You can see migrated (failing) code here.
Any Idea why this isn't working? Can it be because React.Lazy doesn't accept variables?
I get an array like
{Path:xxx,
Component:"./xxx/ComPXX"}
from my API and based on that create my application's routes. At the moment I'm using React-Loadable (5.5.0) and React-Router (4.4.0-betax to avoid warnings in strict mode). See working example here.
Since React 16.6 has introduced React.lazy, I'm trying to migrate my solution, however I'm facing errors and difficulties however I try to do this. You can see migrated (failing) code here.
Any Idea why this isn't working? Can it be because React.Lazy doesn't accept variables?
Share Improve this question edited May 3, 2019 at 14:04 Sagiv b.g 31k10 gold badges72 silver badges104 bronze badges asked Oct 25, 2018 at 10:08 AshaAsha 4,3617 gold badges46 silver badges57 bronze badges1 Answer
Reset to default 9You got 2 3 main issues:
In this line:
var c = <dynamicLoader ponent={prop.ponent} />;
User-Defined Components Must Be Capitalized. so change it to this:
var c = <DynamicLoader ponent={prop.ponent} />;
Obviously you'll need to change the declaration as well:
function DynamicLoader(props) { return ( <Suspense fallback={<div>Loading...</div>}> React.lazy(() => import(`${props.ponent}`)) </Suspense> ); }
In this line
return <Route exact path={prop.path} ponent={c} key={key} />;
As the name of the prop
ponent
suggests, you need to pass a ponent and not an element you can read more about the difference in the DOCS.So you'll need to change it to this:
return <Route exact path={prop.path} ponent={() => c} key={key} />;
You are right. I missed the children part, you are rendering a string. You can create a variable and just render it as the child:
function DynamicLoader(props) { const LazyComponent = React.lazy(() => import(`${props.ponent}`)); return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent/> </Suspense> ); }