Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  177] [ 6]  / answers: 1 / hits: 46985  / 7 Years ago, sat, february 4, 2017, 12:00:00

  • The typical solution to the problem doesn't work in in React due to
    its dynamically generated component structure and event model, as opposed to
    traditional static HTML:



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) />



  • There is a npm package react-iframe, but it looks unfinished
    (accepts only props url, width, height):



    https://www.npmjs.com/package/react-iframe


  • The likely part of the solution is to listen to the load event of
    the iframe, but in a way that is compatible with React.




Is there a way in React to set the height of an iframe to the height of its scrollable contents?



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

More From » css

 Answers
5

What you want to do is in your componentDidMount, run the script to set the height. [If you are loading external content, you might want to add event listener on the IFrame to wait until the external content is loaded.]



   componentDidMount() {
const obj = ReactDOM.findDOMNode(this);
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}


There is another, more reacty way of doing this - where you would store the height in state.



   componentDidMount() {
const obj = ReactDOM.findDOMNode(this);
this.setState({iFrameHeight: obj.contentWindow.document.body.scrollHeight + 'px'});
}


and then in your render:



render() {
return (
<div style={{maxWidth:640, width:'100%', height:this.state.iFrameHeight, overflow:'auto'}}>
{this.renderHTMLFrame()}
</div>
);
}

[#59069] Thursday, February 2, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
triston

Total Points: 545
Total Questions: 88
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;