Skip to content

Instantly share code, notes, and snippets.

@neevai
Created March 21, 2019 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neevai/743b48e5390c46b615833cc08ee3c179 to your computer and use it in GitHub Desktop.
Save neevai/743b48e5390c46b615833cc08ee3c179 to your computer and use it in GitHub Desktop.
React iframe component that listens to messages from the embedded document
import React from 'react';
import PropTypes from 'prop-types';
export default class ReactiveIframe extends React.Component {
static propTypes = {
origin: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
onMessage: PropTypes.func.isRequired,
title: PropTypes.string,
frameBorder: PropTypes.number
};
static defaultProps = {
title: 'reactiveIframe',
frameBorder: 0
};
constructor(props) {
super(props);
this.handleMessage = this.handleMessage.bind(this);
}
componentDidMount = () => window.addEventListener('message', this.handleMessage);
componentWillUnmount = () => window.removeEventListener('message', this.handleMessage);
handleMessage = (messageEvent) => !~messageEvent.origin.indexOf(this.props.origin) ? null : this.props.onMessage(messageEvent.data);
render = () => <iframe title={this.props.title} src={this.props.src} frameBorder={this.props.frameBorder}/>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment