Search code examples
reactjsimportreact-propsreact-component

Import component based on passed prop


Is there a way to import a component based on what was passed from a parent component as a prop, something like

<ComponentA
   componentToLoad = '/path/to/componentB'
/>

and then in the ComponentA do

@import localComponent from {props.componentToLoad};

Solution

  • I was not able to find perfect solution but workaround mentioned below was good enough for me to achieve what I was looking for.

    I have created common table headers index file which contains all locations for table headers:

    tableHeaders.jsx

    let tablelHeaders = {};
    
    tableHeaders['propA'] = require('../tableA/tableAheaders.jsx').default;
    tableHeaders['propB'] = require('../tableB/tableBheaders.jsx').default;
    tableHeaders['propC'] = require('../tableB/tableCheaders.jsx').default;
    ...
    tableHeaders['propX'] = require('../tableX/tableXheaders.jsx').default;
    
    export default tableHeaders
    

    and then in the view for the main component specify prop for that:

    <MyTable tableHeaders="propA" />
    

    and in the MyTable component access it as require instead of import

    MyTable.jsx:

    import tableHeaders from "tableHeaders.jsx;
    
    ....
    
    
    const tableColumns = tablelHeaders[props.tableHeaders];
    
    

    Hope it will helps someone else or somebody else will came up with better solution.