Skip to content Skip to sidebar Skip to footer

Dynamic Instantiation Of Child Components By String Name - Reactjs

I have an array that contains React Component string names ('SampleWidget1'); it's populated by an external mechanism. Within my DashboardInterface component, I'd like to consume t

Solution 1:

for that you should import components and select desired, by key property

1 ) short example

import * as widgets from'./widgets.js';

const widgetsToRender = ["Comp1","Comp2","Comp3"];

classAppextendsComponent {
    render(){
        constWidget = widgets[this.props.widgetsToRender[0]] 
        return<Widget />
    }
}

2 ) Full example webpackbin DEMO


3 ) Example with multiple components

renderWidgets(selected){
    return selected.map(e=>{
      letWidget =widgets[this.props.widgetsToRender[e-1]];
      return<Widgetkey={e}/>
    })
  }

webpackbin DEMO

enter image description here

Post a Comment for "Dynamic Instantiation Of Child Components By String Name - Reactjs"