Reputation: 1091
I have a Container Element and I would like to allow users to select a list of Widgets (Each Widget is different) that a User can choose to add to the container.
I have the following code for WidgetContainer:
export default class WidgetContainer extends React.Component {
constructor(props){
super(props);
console.log('WidgetContainer() : props=['+props+']');
}
render() {
var widgetsTmp = '';
if(this.props.data && this.props.data.widgets){
widgetsTmp = this.props.data.widgets.map(function(widget){
return (
<WidgetItem data={widget} key={widget.id}/>
);
});
}
return (
<div className='container'>
{widgetsTmp}
</div>
);
}
}
And I am setting the props for WidgetContainer as below in an element which contains WidgetContainer
<WidgetContainer data={section}/>
And from my Store I am sending the details of the Widgets using the following JSON Object as initial props.
widgets:
[
{
title:'Widget1',
id:'1'
},
{
title:'Widget2',
id:'2'
}
]
I am not sure how I can specify the Widget it self declaratively?
The other option is using the children's property of the parent and add them using non JSX Syntax.
Upvotes: 0
Views: 3810
Reputation: 159105
If you can get access to the component class, you can assign it to any capitalized variable name and render it normally via JSX.
var CapitalizedVariableName = lookupComponentClass(maybeBySomeString);
return <CapitalizedVariableName props={stuff} />;
So, as a basic example:
import Widget1 from "./widget1";
import Widget2 from "./widget2";
var widgets = {
'Widget1': Widget1,
'Widget2': Widget2
};
// ...
if(this.props.data && this.props.data.widgets){
widgetsTmp = this.props.data.widgets.map(function(widget){
var WidgetType = widgets[widget.type];
return (
<WidgetType data={widget} key={widget.id}/>
);
});
}
Upvotes: 1