Reactjs Render component dynamically based on JSON configuration

I have the following configuration as JSON

var componentConfig = { content: { type: "ContentContent", data: "content"}, new_content: { type: "ContentFormContent", data: "content"} } 

In real rendercomponent, is it possible to dynamically pass the component name for the render reaction.

for example, in this render component, instead of directly placing a ContentFormContent, you can pass data from json config, and I can execute a loop or something else.

 React.renderComponent(<ContentFormContent data={[componentConfig.new_content.data]} />, body); 

SO I will have a list of pages in json config and based on the choice of a particular nav I will display the component based on its "type" from the json file

+8
javascript reactjs
source share
2 answers

Jsx

 <ContentFormContent data={[componentConfig.new_content.data]} /> 

just compiles to

 ContentFormContent({data: [componentConfig.new_content.data]}) 

so that you can make this function call as you like. In this case, it is probably most convenient to make a list of all the possible components and do something like

 var allComponents = { ContentContent: ContentContent, ContentFormContent: ContentFormContent }; // (later...) React.renderComponent(allComponents[component.type]({data: component.data}), body); 

if component is an element from your example array.

+13
source share

React.renderComponent () is deprecated to use React.render () https://facebook.imtqy.com/react/blog/2014/10/28/react-v0.12.html#deprecations

You can do something like:

 var loadReactModule = function ($root, type, data) { var ContentContent= React.createClass({ render: function () { return ( <input type="text" placeholder="My Module-Input"/> ); } }); var ContentFormContent= React.createClass({ render: function () { return ( <form></form> ); } }); var allComponents = { ContentContent: ContentContent, ContentFormContent: ContentFormContent }; if (type in allComponents) { $root.each(function (index, rootElement) { React.render(React.createElement(allComponents[type]), {data:data}, rootElement); }); } }; 
+3
source share

All Articles