- When tackling this problem in a React environment, the traditional solution falls short due to the dynamic component structure and event model:
script:
<script>
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
html:
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
An npm package called
react-iframe
exists, but it seems incomplete as it only accepts specific props likeurl
,width
, andheight
:The possible solution involves listening to the
load
event of theiframe
, but with compatibility for React.
Is there a way in React to adjust the height of an iframe
to match its scrollable content?
my code:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Iframe from 'react-iframe'
export default class FullheightIframe extends Component {
componentDidMount() {
console.log("IFRAME DID MOUNT");
}
renderReactFrame() {
return (
<Iframe url="http://www.example.com" width="100%" height="100%" onLoad={()=>{console.log("IFRAME ON LOAD")}}></Iframe>
);
}
renderHTMLFrame() {
return (
<iframe
onLoad={(loadEvent)=>{
// NOT WORKING var frameBody = ReactDOM.findDOMNode(this).contentDocument.body; // contentDocument undefined
// NOT WORKING obj.nativeEvent.contentWindow.document.body.scrollHeight // contentWindow undefined
}}
ref="iframe"
src="http://www.example.com"
width="100%"
height="100%"
scrolling="no"
frameBorder="0"
/>
);
}
render() {
return (
<div style={{maxWidth:640, width:'100%', height:'100%', overflow:'auto'}}>
{this.renderHTMLFrame()}
</div>
);
}
}