Search code examples
htmlreactjsmarkup

In React dangerouslySetInnerHTML is not working for html tags.


In React dangerouslySetInnerHTML is not working for html tags. it is not even working on homepage of React. Type <h1>this is heading.</h1> Snippet from React homepage

How can i render html tags in React? Why did we pass * for <em> tags in React tutorials ?


Solution

  • On React homepage example they use markdown(markdown does not understand HTML syntax) and library Remarkable., if you want to use only HTML remove Remarkable from rawMarkup method - { __html: this.state.value }

    var HTMLEditor = React.createClass({
      getInitialState: function() {
        return {value: 'Put here <h1>HTML</h1>'};
      },
      
      handleChange: function(e) {
        this.setState({ value: e.currentTarget.value });
      },
      
      markup: function() {
        return { __html: this.state.value };
      },
      
      render: function() {
        return (
          <div className="html-editor">
            <textarea
              onChange={ this.handleChange }
              defaultValue={this.state.value} />
          
            <div
              className="html-editor__content"
              dangerouslySetInnerHTML={ this.markup() }
            />
          </div>
        );
      }
    });
    
    ReactDOM.render(<HTMLEditor />, document.getElementById('container'));
    .html-editor {
      border: 1px solid #000;
      padding: 10px;
    }
    
    .html-editor__content {
      margin: 10px 0 0 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="container"></div>