Given a folder foo
below src
:
.src
..App.js
..foo
...ComponentBah.js
...ComponentFoo.js
...ComponentBaz.js
...ComponentBar.js
Each of the components Bah, Foo, etc export a component matching their filename e.g. ComponentBah.js
exports ComponentBah
. I'd like to write a Route
in App.js
that loads an arbitrary component from /src/foo
based on its name. I.e. if a component ComponentTau
is added to folder foo
, some url such as /path/to/route/ComponentTau
will load the component without needing to update App.js
Create a file index.js
inside foo
as follows:
export default [
'ComponentBah',
'ComponentFoo',
'ComponentBaz',
'ComponentBar'
]
Now you can dynamically add these components as routes in your main router as follows:
import React, { Suspense, lazy } from 'react';
import routes from './path/to/route';
const routeMap = {};
routes.forEach((route) => {
routeMap[route] = lazy(() => import(`./path/to/route/${route}`));
});
function withSuspense(WrappedComponent) {
return function(props) {
return (
<Suspense fallback={<div>Loading...</div>}>
<WrappedComponent {...props} />
</Suspense>
);
};
}
function Router() {
return (
<BrowserRouter>
<div>
{routes.map(route => (
<Route path={`/path/to/route/${route}`} component={routeMap[route]} />
))}
</div>
</BrowserRouter>
);
}
But there are two pitfalls in this approach :
index.js
file.