Zachary Iles
Zachary Iles

Reputation: 161

React dangerouslySetInnerHTML and iframes

I have a componenet that renders a Wordpress blog post. The blog post contains regular text/html markup and sometimes also includes youtube embeds with an element. dangerouslySetInnerHTML strips out this iframe. How can I support this type of content.

Upvotes: 1

Views: 2586

Answers (1)

Duncan Thacker
Duncan Thacker

Reputation: 5188

You can get around this by creating a React element which never updates, but on creation inserts the html you want using regular Javascript. Be aware that this pretty unsafe!

const StaticHtml = React.createClass({
  inject( element ) {
     element.innerHTML = this.props.html;
  },
  
  shouldComponentUpdate() {
     return false;   //prevent React updates as it will get confused by the DOM it didn't put there!
  },
  
  render() {
     return <div ref={ this.inject } />
  }
});

const myHtml = `<iframe width="560" height="315" src="https://www.youtube.com/embed/jUjh4DE8FZA" frameborder="0" allowfullscreen></iframe>`;
ReactDOM.render( <StaticHtml html={ myHtml } />, document.getElementById("app") );
<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='app'></div>

You can't update the value of the "html" prop because React will get confused, so make sure to destroy and re-create the element whenever html changes (the "key" prop is good for this).

Upvotes: 4

Related Questions