Josh
Josh

Reputation: 35

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()} />
    );
  }
});

Upvotes: 3

Views: 9291

Answers (1)

David L. Walsh
David L. Walsh

Reputation: 24817

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>

);

Upvotes: 8

Related Questions