Reputation: 191
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
Upvotes: 17
Views: 58912
Reputation: 402
This string-to-react-component library can help you to achieve your desired functionality
Upvotes: 0
Reputation: 15640
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.
But try to avoid rendering text as much as possible, since it might expose you to XSS attacks, you should XSS clean the text or avoid this unless you have no choice
Upvotes: 3
Reputation: 4984
one 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
Upvotes: 0
Reputation: 769
This react-jsx-parser component looks like it will solve your problem
Upvotes: 12
Reputation: 22553
If 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.
Upvotes: 2
Reputation: 4343
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
Upvotes: 9