Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: using React component inside of dangerouslySetInnerHTML

Tags:

reactjs

I have a question about using React. As you can see from the title, I'm wondering if it is possible to use React component (that is created by React.createClass) inside of dangerouslySetInnerHTML property. I have tried, but React just prints code without transformation like this:

const MySubComponent = React.createClass({
    render() {
        return (<p>MySubComponent</p>);
    }
});

...

let myStringHTML;
myStringHTML += "<ul>";
myStringHTML += "    <li>";
myStringHTML += "        <MySubComponent />";
myStringHTML += "    </li>";
myStringHTML += "</ul>";

const MyComponent = React.createClass({
    render() {
        return (
            <div dangerouslySetInnerHTML={{__html:myStringHTML}}></div>
        );
    }
});

I expected

<ul>
    <li>
        <p>MySubComponent</p>
    </li>
</ul>

but the code is just same as original string, and that means React didn't transform MySubComponent.

Is there a way to solve this problem? Above example is just simple but my actual code is quite complicated. It will be very thanks gimme a hand ;)

like image 678
modernator Avatar asked May 02 '16 09:05

modernator


1 Answers

Another approach would be to open a react portal. Ensure that the element has rendered and then simply

ReactDOM.createPortal(<YourComponent>,document.querySelector('selector'));

This is the cleanest way so far i have found to achieve this.

like image 182
Riyo Avatar answered Oct 21 '22 01:10

Riyo