How to render a string with JSX in React

I need to render an HTML (JSX) string in a React class. I don't know if this is possible or not. dangerouslySetInnerHTML is not valid for me because I have different react components inside this file. It's not plain HTML.

I have an example with the expected result: https://jsfiddle.net/86rg50re/1/

var MyComponent = React.createClass({
    propTypes: {
        owner: React.PropTypes.string
    },

    render: function() {
        return <div>Congrats {this.props.owner}! you have rendered MyComponent ({this.props.children})</div>;
    }
});

var Hello = React.createClass({
    render: function() {
        return <div>Header <MyComponent owner={"Daniel"}>Yayyyyyy!</MyComponent></div>;
    }
});

But what I have is this:

var Hello = React.createClass({
    render: function() {
        var content = '<div>Header <MyComponent owner={"Daniel"}>Yayyyyyy!</MyComponent></div>';
        return transformStringToJSX(content);
    }

Obviously transformStringToJSX doesn't exists.

Is there a way to render jsx strings?


You can use babel to transform it

npm install --save babel-core

Then in your code

var babel = require('babel-core');
var Component = eval(babel.transform('<div><MyComponent /></div>').code);

Please note that it is generally a bad idea to convert strings to executable code.

链接地址: http://www.djcxy.com/p/52094.html

上一篇: React JSX:在Maped组件列表中的行情中访问道具

下一篇: 如何在React中使用JSX呈现字符串