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
To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).
React component can return only string, it's perfectly valid (and works as OP stated) ... but this use case is not supported. Using components to just return a string is not a good choice. It can be ineffective when you need many translated strings in one component.
React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM. render() .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With