I want to render the react components with a string as the input which i am receiving dynamically from another page. BUt i will have the references for the react components. Here is the example
Page1:
-----------------------------
loadPage('<div><Header value=signin></Header></div>');
Page2:
--------------------------------
var React =require('react');
var Header = require('./header');
var home = React.createClass({
loadPage:function(str){ this.setState({ content : str }); }, render : function(){ return {this.state.content} }
});In this example i am receiving Header component as string , and i have the reference of Header component in my receiving page . How can i substitute the string with the actual react component
55 Answers
This react-jsx-parser component looks like it will solve your problem
To render a react component using a string you can use.
var MyComponent = Components[type + "Component"];
return <MyComponent />;For more information check the response here : React / JSX Dynamic Component Name
2If you can live with having all your components in one module, then this works pretty well:
import * as widgets from 'widgets'; var Type = widgets[this.props.componentId]; ... <Type />The wildcard import works like a cut-rate component registry.
Built in way
Without any package You can use the built in react attribute dangerouslySetInnerHTML to pass your string, and it will render it as an HTML
function Component() { const stringElement = "<h1> My Title </h1>"; return ( <div dangerouslySetInnerHTML={{ __html: stringElement }}> </div> );
}And it would work fine
2one more way to use component
const a = { b: { icon: <component props /> }
}In render function
return( {a.b.icon} )This will render your component in your JSON object