Search code examples
javascriptreactjsreact-dom

React DangerouslySetInnerHTML


How Can I render Component children as Html with react dangerouslySetInnerHtml, if I set text it works fine, but if I set Html this return [object Object]

    class App extends React.Component{
  render(){
    return(
      <div dangerouslySetInnerHTML={{__html: this.props.children}}>

      </div>
    )
  }
}

1) ReactDOM.render(
  <App> Test </App>,
 document.getElementById('root')); --- Works


2) ReactDOM.render(
  <App> <p>Test</p> </App>,
 document.getElementById('root')); --- return [object Object]

Link to JS Bin


Solution

  • As I explained in the comments, you are getting [object Object] in the output because __html needs to be a string, but you are passing the React Component created from <p>Test</p>.

    It is still unclear for me why you want to do this, but to do what you are asking for you need to pass a string.

    So you can do one of the following:

    <App>{"<p>Test</p>"}</App>
    

    or

    <App children="<p>Test</p>" />
    

    both are equivalent and pass your markup as a string, which will then become the value for __html.


    Note!

    This will only work for normal HTML - not React Components written in JSX!

    For example, this will not work:

    <App children="<Foo>Test</Foo>" />