Reputation: 1715
Is it possible to dynamically render a React component from a string?
Basically I have pages' content coming from a database and I want to have React components within the content. An example of what I'm trying to achieve:
var html_string = '<i>React Component Rendered</i>: <Hello name="World" />';
var Hello = React.createClass({
render: function() {
return <strong>Hello {this.props.name}</strong>;
}
});
function createMarkup() { return {__html: html_string}; };
var App = React.createClass({
render: function() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
});
ReactDOM.render(
<App/>,
document.getElementById('container')
);
But it just renders the HTML without evaluating <Hello />
:
<div><i>React Component Rendered</i>: <hello name="World"></hello></div>
I'm trying to get:
<div><i>React Component Rendered</i>: <strong>Hello World</strong></div>
Example on JSFiddle
Upvotes: 2
Views: 7429
Reputation: 799
Might be a little late to the party one this one, but have found myself needing to do slightly similar to this and after searching the web, I've found that this is actually technically possible now (safety issues aside) - with the addition of a nice little react package:
https://github.com/TroyAlford/react-jsx-parser
import React, { Component } from 'react'
import JsxParser from 'react-jsx-parser'
class InjectableComponent extends Component {
// ... inner workings of InjectableComponent
}
class MyComponent extends Component {
render() {
/* Pull out parent props which shouldn't be bound,
then pass the rest as `bindings` to all children */
const { prop1, prop2, ...bindings } = this.props
return (
<JsxParser
bindings={bindings}
components={{ InjectableComponent }}
jsx={'\
<h1>Header</h1>\
<InjectableComponent />\
'}
/>
)
}
}
all credit to TroyAlford!
Upvotes: 3
Reputation: 482
As thangngoc89 as said there is no way to do this. At least no simple way.
JSX is transpiled into javascript, it only syntactically looks like xml.
this:
var x = <div> <i>React Component Rendered</i>: <Hello name="World" /> </div>;
is mapped to:
var x = React.createElement(
"div",
null,
" ",
React.createElement(
"i",
null,
"React Component Rendered"
),
": ",
React.createElement(Hello, { name: "World" }),
);
A better strategy would probably be to parse the database elements and then dynamically render the result of the db query using react (this also promotes looser coupling).
Upvotes: 2
Reputation: 1400
what you are asking is not possible. React will dump what ever string you provided via dangerouslySetInnerHTML
. It will not evaluating anything inside it.
Upvotes: 0