React
Install
Install this package with the following command.
You will also need to ensure that the @iframe-resizer/child package has been loaded into every page that loads into the iframe.
Usage
The <IframeResizer />
component can be passed all<iframe>
attributes, along with
options and events from iframe-resizer.
You can also optionally pass a forwardRef
to gain access to a few methods
that provide a simple interface to communicate with the page in the iframe.
Typical setup
The normal configuration is to have the iframe resize when the browser window changes size or the content of the iframe changes. To set this up you need to configure one of the dimensions of the iframe to a percentage and tell the library to only update the other dimension. Normally you would set the width to 100% and have the height scale to fit the content.
Setting the initial height of the iframe to 100vh
makes the loading in of
the iframe appear smoother to the user, as they will only see the content
below the iframe once it has completed loading and undergone it’s initial
sizing.
The waitForLoad
option defers sending a message to the iframe until after
the onload
event fires on the iframe. If their is any possibility that the
iframe content could load before the JavaScript runs, then you should set
this option to false. This is only likely to be an issue with server
side rendering.
Child page
You will then need to install the @iframe-resizer/child package on every page in the iframe.
API Differences
The React version of iframe-resizer supports the Parent Page API with
a couple of minor changes to the available methods. To access these methods you need to
pass a forwardRef
as follows.
disconnect()
This method is not available, use React to remove the iframe from the page.
getElement()
Returns the iframe element.
getRef()
Returns a ref to the iframe.
Advanced Example
This is a more advanced configuration, which demonstrates the use of options, events and methods from the Parent Page API.
The <MessageData/>
component is then used to display some of the data returned from the iframe.