Skip to content

Instantly share code, notes, and snippets.

@mihkeleidast
Created April 25, 2018 14:21
Show Gist options
  • Save mihkeleidast/14360929f92c307feb06b146a8c379eb to your computer and use it in GitHub Desktop.
Save mihkeleidast/14360929f92c307feb06b146a8c379eb to your computer and use it in GitHub Desktop.
react-iframe-resizer
/**
*
* inject script to facilitate iframe resizing
* https://github.com/davidjbradshaw/iframe-resizer
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { iframeResizer as iframeResizerLib } from 'iframe-resizer';
class IframeResizer extends React.Component {
componentDidMount() {
// can't update until we have a mounted iframe
this.resizeIframe(this.props);
}
componentWillReceiveProps(nextProps) {
// can replace content if we got new props
this.resizeIframe(nextProps);
}
componentWillUnmount() {
if (this.iframeResizer.length && this.iframeResizer[0].iFrameResizer) {
this.iframeResizer[0].iFrameResizer.close();
}
}
resizeIframe(props) {
const frame = this.refs.frame;
if (!frame) return;
if (props.iframeResizerEnable) {
console.log('setup iframe-resizer');
this.iframeResizer = iframeResizerLib(props.iframeResizerOptions, frame);
}
}
render() {
const { src, id, frameBorder, className, style } = this.props;
return (
<iframe
ref="frame"
src={src}
id={id}
frameBorder={frameBorder}
className={className}
style={style}
/>
);
}
}
IframeResizer.propTypes = {
// option 2. src to a URL to load in the iframe
src: PropTypes.string,
// iframe-resizer controls and helpers
iframeResizerEnable: PropTypes.bool,
iframeResizerOptions: PropTypes.object,
// misc props to pass through to iframe
id: PropTypes.string,
frameBorder: PropTypes.number,
className: PropTypes.string,
style: PropTypes.object,
// optional extra callback when iframe is loaded
// onIframeLoaded: PropTypes.func,
};
IframeResizer.defaultProps = {
// resize iframe
iframeResizerEnable: true,
iframeResizerOptions: {
// log: true,
// autoResize: true,
// checkOrigin: false,
// resizeFrom: 'parent',
// heightCalculationMethod: 'max',
// initCallback: () => { console.log('ready!'); },
// resizedCallback: () => { console.log('resized!'); },
},
// misc props to pass through to iframe
frameBorder: 0,
style: {
width: '100%',
minHeight: 20,
},
};
export default IframeResizer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment