score:4
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>
);
}
score:0
the best and reliable way to fit iframe is to use
iframe-resizer package.
https://www.npmjs.com/package/iframe-resizer
score:0
just use usestate and useeffect with settimeout with 100miliseconds and you are done
const [frameheight , setframeheight] = usestate()
useeffect(() => {
const frame = document.getelementbyid('myframe');
console.log("height" , frame.contentwindow.document.body.scrollheight + "px")
settimeout(() => {
setframeheight(frame.contentwindow.document.body.scrollheight + "px")
},100)
},[])
return (
<iframe srcdoc={content}
id="myframe"
width="100%"
height={frameheight}
frameborder="0"
scrolling="no"
></iframe>
)
you'r welcome !
score:1
none of the answers proposed so far worked for me. the hackish approach of doing a short settimeout
from within onload
kind-of seems to do the job, at least in my case.
class smartiframe extends react.component {
render() {
return <iframe srcdoc={this.props.srcdoc}
scrolling="no"
frameborder={0}
width="100%"
onload = {e => settimeout(() => {
const obj = reactdom.finddomnode(this);
obj.style.height = obj.contentwindow.document.body.scrollheight + 'px';
}, 50)}/>
}
}
score:1
this npm package will do what you what, it offers a range of different ways to calculate the height of the content in the iframe
https://www.npmjs.com/package/iframe-resizer-react
with this use case it can be configured as follows
<iframeresizer
heightcalculationmethod="bodyscroll"
src="http://anotherdomain.com/iframe.html"
/>
score:7
a couple of things to note here:
- you can use refs to get a reference to the iframe instead of having to search for it
- use the onload() handler from the iframe to ensure that the content has loaded before you try to resize it - if you try to use react's lifecycle methods like
componentdidmount()
you run the risk of the content not being present yet. - you will likely also want a resize handler to ensure the iframe gets resized as needed - just be sure to clean it up when the component unmounts.
- you have to be careful of how different browsers report the height. go for the largest you can find.
- you may have issues if the iframe content is in a different domain than your code. there are solutions out there such as react-iframe-resizer-super that try to solve this problem in a cross-domain compatible way.
class wrappedframe extends react.component {
state = { contentheight: 100 };
handleresize = () => {
const { body, documentelement } = this.container.contentwindow.document;
const contentheight = math.max(
body.clientheight,
body.offsetheight,
body.scrollheight,
documentelement.clientheight,
documentelement.offsetheight,
documentelement.scrollheight
);
if (contentheight !== this.state.contentheight) this.setstate({ contentheight });
};
onload = () => {
this.container.contentwindow.addeventlistener('resize', this.handleresize);
this.handleresize();
}
componentwillunmount() {
this.container.contentwindow.removeeventlistener('resize', this.handleresize);
}
render() {
const { contentheight } = this.state;
return (
<iframe
frameborder="0"
onload={this.onload}
ref={(container) => { this.container = container; }}
scrolling="no"
src="your.source"
style={{ width: '100%', height: `${contentheight}px` }}
title="some content"
/>
);
}
}
in this example we're storing the determined content height in the component's state and using that state to set the height of the rendered iframe. also, by putting the onload()
handler definition in the component, you save a tiny bit of performance in render()
by not creating a new handler function on every re-render.
score:12
here is the answer, but first two important things.
- iframe has to be the root component in the
render()
method - the height has to be captured from the
onload
event (once the iframe if fully loaded)
here is the full code:
import react, { component, proptypes } from 'react'
import reactdom from 'react-dom'
export default class fullheightiframe extends component {
constructor() {
super();
this.state = {
iframeheight: '0px'
}
}
render() {
return (
<iframe
style={{maxwidth:640, width:'100%', height:this.state.iframeheight, overflow:'visible'}}
onload={() => {
const obj = reactdom.finddomnode(this);
this.setstate({
"iframeheight": obj.contentwindow.document.body.scrollheight + 'px'
});
}}
ref="iframe"
src="http://www.example.com"
width="100%"
height={this.state.iframeheight}
scrolling="no"
frameborder="0"
/>
);
}
}
Source: stackoverflow.com
Related Query
- Setting iframe height to scrollHeight in ReactJS
- Setting iframe height to scrollHeight in ReactJS using IframeResizer
- Setting iframe height to scrollHeight in GatsbyJS
- Get viewport/window height in ReactJS
- ReactJS - Get Height of an element
- Reactjs - setting inline styles correctly
- ReactJS get rendered component height
- How to integrate Youtube Iframe api in reactjs solution
- Embedding Reactjs in Remote Site iFrame
- Reactjs - Get Height of a div/image using React Hooks
- Setting Up ReactJS on .NET Core 2.0, InvalidOperationException
- Reactjs - Setting State from props using setState in child component
- ReactJs with Iframe events and changes handling
- React Native SVG - Setting SVG width and height cause the icon to be cut off
- How to set Height of ComboBox Autocomplete of Material UI using ReactJS
- React Apexchart is not taking its parent height when setting height 100%
- ReactJS - How to render iframe inner contents server-side, for SEO?
- ReactJS MaterialUI Checkboxes- setting state within onCheck()
- ReactJS - Silently renew token with iframe
- ReactJS - CSS: setting trasitionProperty in style object does not work
- Why does setting the allowfullscreen attribute of an iframe doesn't seem to keep the attribute
- ReactJS Change Navbar color based on scroll to section with dynamic height
- How to properly implement scrollHeight or scrollTop for div messages using Reactjs
- ReactJS setting css classes based on props
- ReactJS get ref to child element and setting its scrollTop position
- setState in reactjs inside success function not setting state
- reactjs svg image rendered with zero width and height in IE
- What is the correct way of setting state variables in Reactjs and what is the difference between these approaches?
- Setting state in a subcomponent of react-table closes component resetting all states with ReactJS
- ReactJS difference between setting state directly and through method argument
More Query from same tag
- react - function inside useEffect
- how to use usestate with node.js backend and react frontend
- Dispatching redux-thunk actions without importing
- How to pass a function through props in React to a function in a different component?
- How can I add onClick event for Ref Element using React Hooks?
- selecting child react component under div is not working in app.jsx file
- React component rerender multiple times
- react-pdf/renderer - Cannot read properties of undefined (reading 'height')
- create-react-app not working when added to android home screen
- React avoid lowercase conversion on null objects
- Filtering Mapped React Table Data with JSON Data
- Error: Javascript identifier already been declared inside switch when deconstructing variable
- how to setInterval on redux action without re-rendering the whole app
- Navbar component not loading with react and react-bootstrap
- Why is only the last item in a map function being changed in react app?
- How to find the position of item in an embedded object
- Can't use mobs decorator, error:Support for the experimental syntax 'decorators-legacy' isn't currently enabled
- react useEffect trigger although dependency value remain the same?
- Can you help me with layouts on react native app?
- React Native: Problem with dependencies and archiving my project
- InitialState not updated in React-Redux
- Change table data set based on Google Maps API results
- How do I catch and parse errors properly in my React form submission handler?
- Export not working for connected component in react
- Using useEffect hook when unmounting with dynamic props
- React: AutoFocus on Input field inside Modal
- Limit content editable table data input to only one number with one decimal
- React & Jest: Cannot find module from test file
- Grunt, Jasmine, Phantom, React Unit Testing: React throws on ReactElementValidator
- React expose component function and getting data with ComponentDidMount