Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React dangerouslySetInnerHTML to render an iframe youtube embed from props?

Anybody have any idea how to get this prop attribute to stringToHTML in React? Thanks in advance!

var Video = React.createClass({

getDefaultProps: function getDefaultProps() {

        return propsObj;
},

createMarkup: function() { 

    return {__html: {this.props.video}}; 
},

  render: function() {
    return (

      <div className="video-container no-controls" id="player" dangerouslySetInnerHTML={createMarkup()} />
    );
  }
});
like image 278
Josh Avatar asked Feb 21 '26 14:02

Josh


1 Answers

There's a reason why HTML injection in React has such a cumbersome API: its use is strongly discouraged.

It's not obvious why you would want to use HTML injection for something as straightforward as a YouTube video iframe. The markup for it is quite predictable.

I strongly urge you to rewrite it in JSX. Here's the code for a YouTube component I used in a recent project.

const YouTubeVideo = ({ id }) => (

    <div className="youtube-wrapper">
        <div className="youtube">
            <iframe
                className="youtube-frame"
                src={`https://www.youtube.com/embed/${id}?autoplay=1`}
                allowFullScreen
            />
        </div>
    </div>

);
like image 113
David L. Walsh Avatar answered Feb 23 '26 03:02

David L. Walsh