Alisson Alisson - 2 years ago 398
Javascript Question

React render components from string

Is it possible to dynamically render a React component from a string?

Basically I have pages' content coming from the database and I want to have React componentes 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>


This example on JSfiddle: https://jsfiddle.net/26czprne/

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download