How to pass a React component (or raw html) into another React component and insert it?

advertisements

I have raw html markup returned from ajax. Rendering raw html is not easy in React. I tried to use their dangerouslySetInnerHTML up and down but no go, only errors are thrown from React. That dangerouslySetInnerHTML is truly obscure.

So I decided to compile my raw html to a React component and insert it. Raw html is compiled to React component all right but I cannot insert it. Here is my code. I want to pass <Html /> component (or raw html would be even better) to <Tr /> component as this.props.b:

var FooComponent = React.createClass({
    render: function() {
            var Html = React.createClass({
                render: function() {
                    return (
                        myRawHtmlMarkup
                    );
                }
            });

        return (
            <Tr id={key} a={value} b={Html} />
        );
    }
});

Now how to insert either raw html or <Html /> into DOM <td> element? Using {this.props.b} doesn't work.

And the inportant thing here is that I cannot change this.props.b to smth else like this.props.child, this.props.children, etc. I need that this.props.b because there is a loop in parent FooComponent component and I assign values to this.props.b using many if/else conditions (not shown above for the sake of simplicity):

var Tr = React.createClass({
    render: function() {
        return (
            <tr>
                <td className="idCol">{this.props.id}</td>
                <td className="aCol">{this.props.a}</td>
                <td className="bCol">{this.props.b}</td>
            </tr>
        );
    }
});


The render method in your Html component will throw an error, because a component needs to return a valid ReactComponent, not a string.

I think you could parse the HTML and append as children in componentDidMount: https://jsfiddle.net/4z13gp7g/

var Tr = React.createClass({
    componentDidMount: function(){
    var div = document.createElement('div');
    div.innerHTML = this.props.b;
    this.refs.b.appendChild( div.firstChild )
  },
    render: function() {
        return (
            <tr>
                <td className="idCol">{this.props.id}</td>
                <td className="aCol">{this.props.a}</td>
                <td className="bCol" ref="b"></td>
            </tr>
        );
    }
});

ReactDOM.render(
   <Tr id="key" a="value" b="<p><strong>Hi</strong></p>" />,
   document.querySelector('table tbody')
);