Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering iframe into React

Tags:

reactjs

meteor

I've got the following component:

export default class VideoArchiveContent extends React.Component {
  constructor() {
    super();
    this.state = {
      videos: []
    }
  } 
  componentDidMount() {
    this.VideosTracker = Tracker.autorun(() => {
      Meteor.subscribe('videos');
      const videos = Videos.find().fetch();
      this.setState({ videos })
    });
  };
  componentWillUnmount() {
    this.VideosTracker.stop();
  };
  renderVideos = () => {
    return this.state.videos.map((video) => {
      return <div key={video._id}>{video.embed}</div>
    });
  };
  render() {
    return (
      <div>
        {this.renderVideos()}
      </div>
    )
  }
};

I'm expecting the iframe to render to the screen. What renders is the iframe string.

If I place the iframe in the return statement like this:

return (
  <div>
    <iframe src="https://player.vimeo.com/video/270962511" width="500" height="281" frameborder="0" allowfullscreen></iframe>
  </div>
)

The iframe renders as expected.

Is there a solution?

like image 916
flimflam57 Avatar asked Mar 07 '23 04:03

flimflam57


1 Answers

I'm not sure where is the iframe comes from as i don't see it in your code as an HTML tag so i'm guessing it is coming from the server as a string. Probably inside video.embed.
If this is the case then you would need to use the dangerouslySetInnerHTML attribute to render this:

return <div key={video._id} dangerouslySetInnerHTML={{__html:video.embed}} />

Use it with caution, I advice to read about it in the DOCS first.

Running example:

const tweetersIframe = '<iframe src="https://platform.twitter.com/widgets/tweet_button.html" />'
const App = () => (
  <div dangerouslySetInnerHTML={{ __html: tweetersIframe}}>
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));
<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="root"></div>
like image 158
Sagiv b.g Avatar answered Mar 17 '23 04:03

Sagiv b.g