React: dynamic import jsx

后端 未结 3 680
鱼传尺愫
鱼传尺愫 2021-02-04 18:55

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

相关标签:
3条回答
  • 2021-02-04 19:28

    To complement @gor181's answer, I can add that exports must be this way:

    export { default as CompA } from "./comp_a"; export { default as CompB } from "./comp_b";

    Hope this might be helpful.

    0 讨论(0)
  • 2021-02-04 19:36

    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
    <Switch>
      …
      <Route path="/somewhere/:componentName" component={MyDynamicComponent} />
    </Switch>
    

    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 = () => <div>This component does not exist.</div>;
        const dynamicComponent = (() => {
          const MyComponent = Views[`${componentName}View`]
            ? Views[`${componentName}View`]
            : Empty;
          return <MyComponent key={shortid.generate()} />;
        })();
    
        return (
          <>
            <Suspense fallback={<div>Loading…</div>}>{dynamicComponent}</Suspense>
          </>
        );
      }
    }
    MyDynamicComponent.propTypes = {
      match: PropTypes.shape({
        params: PropTypes.shape({
          componentName: PropTypes.string.isRequired,
        }),
      }),
    };
    
    export default MyDynamicComponent;
    

    Usage

    {items.map(item => (
      <NavLink to={`/somewhere/${item.componentName}`}>
        {item.name}
      </NavLink>
    ))}
    
    0 讨论(0)
  • 2021-02-04 19:44

    What about having a components/index.js with contents:

    export CompA from "./comp_a";
    export CompB from "./comp_b";
    

    Then you do:

    import * as Components from "./components"
    

    then you would use as:

    <Components.CompA />
    <Components.CompB />
    ...
    

    Hope this helps.

    I doubt you can load anything when sending path through component props, loading of the file should then happen inside the React component lifecycle methods which is not something I would recommend.

    0 讨论(0)
提交回复
热议问题