This question related to dynamically importing JSX files into React.
Basically we have one main component that dynamically renders other components based on a structure
As of React 16.6.0, we can lazy-load components and invoke them on-demand.
The Routing
// We pass the name of the component to load as a param
…
views/index.js
import { lazy } from 'react';
const SomeView = lazy(() => import('./SomeView'));
const SomeOtherView = lazy(() => import('./SomeOtherView'));
export { SomeView, SomeOtherView };
MyDynamicComponent.js
import React, { Suspense, Component } from 'react';
import { PropTypes } from 'prop-types';
import shortid from 'shortid'; // installed separately via NPM
import * as Views from './views';
class MyDynamicComponent extends Component {
render() {
const {
match: {
params: { componentName },
},
} = this.props;
const Empty = () => This component does not exist.;
const dynamicComponent = (() => {
const MyComponent = Views[`${componentName}View`]
? Views[`${componentName}View`]
: Empty;
return ;
})();
return (
<>
Loading…
Usage
{items.map(item => (
{item.name}
))}