-
-
Save BetterProgramming/cd161c1a720505a05d2e525a3c133b33 to your computer and use it in GitHub Desktop.
import React from 'react'; | |
const Iframe = (props) => { | |
let iframe_ref = null; | |
const writeHTML = (frame) => { | |
if (!frame) { | |
return; | |
} | |
iframe_ref = frame; | |
let doc = frame.contentDocument; | |
doc.open(); | |
doc.write(props.content); | |
doc.close(); | |
frame.style.width = '100%'; | |
frame.style.height = `${frame.contentWindow.document.body.scrollHeight}px`; | |
}; | |
return ( | |
<iframe src="about:blank" scrolling="no" frameBorder="0" ref{writeHTML} | |
/> | |
); | |
}; | |
export default Iframe; |
and also would be good to wrap your adding of height. Becuase sometime document inside your frame are still loading and height is still counting.
frame.addEventListener('load', () => {
frame.style.height = `${frame.contentWindow.document.body.scrollHeight}px`;
})
and even better use not body.scrollHeight, but html.scrollHeight
i mean frame.contentDocument.documentElement.scrollHeight instead of frame.contentDocument.body.scrollHeight
@Andrii256: could you post the updated script with the changes you proposed?
I agree: frame.contentDocument.documentElement.scrollHeight
seems to be better.
I get error with frame.contentDocument.body.scrollHeight
Also, how to handle changes in the height of the content? E.g. if there are items that collapse and expand to be displayed within the Iframe?
Simply loading it during onload doesn't suffice.
I dint try it so I'm not sure that it will help with Iframe, but it looks like there resizeObserver API. Possibly it can halp:) https://stackoverflow.com/questions/14866775/detect-document-height-change
nice work
nice stuff, but its better to use React.createRef way, because in this case you can subscribe props changes for changing of frame actually