React-rails: Inserting Raw HTML

Created on 10 May 2016  路  7Comments  路  Source: reactjs/react-rails

I have another issue to discuss.


I am trying to print raw html in the render method. This is what i have done

Sample Component File

var SampleComponent = React.createClass({
    render: function() {

        return (
           <div>
               {this.props.html}
           </div>
        );
    }
});

ERB File

<%= react_component('SampleComponent', html: '<h1>This is a HTML</h1>') %>

Expected output

This is a HTML

Actual Output

<h1>This is a HTML</h1>

How do I achieve this using react-rails gem?

Most helpful comment

For anyone who stumbles upon this from Google since it is one of the first results for how to render raw HTML in React, the above syntax is not correct. The correct syntax is:

<div dangerouslySetInnerHTML={{__html: this.props.html}} />

All 7 comments

To render markup from string in React you must use __dangerouslySetInnerHTML: https://facebook.github.io/react/tips/dangerously-set-inner-html.html

So, you could change your component to:

var SampleComponent = React.createClass({
    render: function() {
        return (
           <div dangerouslySetInnerHTML={{__html: this.props.html}} />
           </div>
        );
    }
});

@kaushik-sundar I was trying to do something similar much earlier in the life of this project. This code may not work now, but you can see how I proposed accomplishing it in this old pr

@danott @rmosolgo Thanks.

For anyone who stumbles upon this from Google since it is one of the first results for how to render raw HTML in React, the above syntax is not correct. The correct syntax is:

<div dangerouslySetInnerHTML={{__html: this.props.html}} />

@kaushik-sundar => https://reactjs.org/docs/dom-elements.html

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

Is there a "sanitize" method that goes along with this, that would maybe remove some elements, maybe you could even which choose which elements to sanitize out?

@Tectract You should be sanitizing your own input for your own use case and using the tools react gives. There's nothing specific to this tool that will help you in this regard.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

okolomoets picture okolomoets  路  5Comments

hugofloss picture hugofloss  路  4Comments

ttanimichi picture ttanimichi  路  4Comments

chrismv48 picture chrismv48  路  3Comments

adoseofjess picture adoseofjess  路  4Comments