question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Adjust height of iframe based on the height of content inside

See original GitHub issue

As the content inside the iframe keeps changing, i want the height of the iframe to adjust accordingly. Looks like there is no way to do it with css alone. I need to set the height of the iframe in javascript on component updates.

I tried the following approach -

<Frame
    {...propsToFrame}
>
   <Resizer />
    <MyContent />
</Frame>

class Resizer extends React.Component {
    static contextTypes = {
        window: PropTypes.any,
        document: PropTypes.any
    }

    adjustHeight = () => {
        if (this.context && this.context.document) {
             // set the frame height to this.context.document.body.scrollHeight
             // but how do i get access to the iframe DOM element
        }
    }

    constructor(props, context) {
        super(props, context)
    }

    componentDidMount() {
        this.adjustHeight()
    }

    componentDidUpdate() {
        this.adjustHeight()
    }

    render() {
        return null
    }
}

I am not able to figure out how to get hold of the iframe DOM element. I tried passing a ref prop to the Frame element, but am not able to reach the DOM iframe element.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:4
  • Comments:20 (2 by maintainers)

github_iconTop GitHub Comments

19reactions
kmaidcommented, Apr 10, 2019

I managed to get something working. I ended up wrapping the frame into another component and using the lifecycle methods of the parent component as the ones provided by the library are fired before the refs are made (which in my opinion is a bug with the library). Here is my code good luck 😃

interface IProps {
  children: React.ReactNode;
}

interface IFrame {
  node: HTMLIFrameElement;
}
export const HeightChangingFrame: React.FunctionComponent<IProps> = ({
  children
}) => {
  const [height, setHeight] = useState(500);
  const iframeRef: React.RefObject<IFrame> = React.createRef();
  const handleResize = (iframe: React.RefObject<IFrame>) => {
    if (
      iframe.current &&
      iframe.current.node.contentDocument &&
      iframe.current.node.contentDocument.body.scrollHeight !== 0
    ) {
      setHeight(iframe.current.node.contentDocument.body.scrollHeight);
    }
  };
  useEffect(() => handleResize(iframeRef), [children]);
  return (
      <Frame
        style={{
          height,
        }}
        ref={iframeRef}
        onLoad={() => handleResize(iframeRef)}
      >{children}</Frame>
  );
};
7reactions
cschroetercommented, Nov 18, 2020

Small refactoring to ensure typescript won’t complain

import React, { useState, useEffect, useCallback, RefObject } from "react";
import Frame from "react-frame-component";

interface FrameRef extends Frame {
  node: HTMLIFrameElement;
}

export const IFrame: React.FC = (props) => {
  const { children } = props;
  const [height, setHeight] = useState(500);
  const iframeRef = React.createRef<FrameRef>();

  const handleResize = useCallback((iframe: RefObject<FrameRef>) => {
    const height = iframe.current?.node.contentDocument?.body.scrollHeight ?? 0;
    if (height !== 0) {
      setHeight(height);
    }
  }, []);

  useEffect(() => handleResize(iframeRef), [handleResize, iframeRef]);

  return (
    <Frame
      ref={iframeRef}
      style={{
        height,
      }}
      onLoad={() => handleResize(iframeRef)}
    >
      {children}
    </Frame>
  );
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

make iframe height dynamic based on content inside
height = ""; (or setting it to '20px' instead) is necessary if you ever need resizeIframe to make an iframe smaller than it...
Read more >
Resize an iframe based on the content - GeeksforGeeks
We select iframe within script tag: var iframe = document.getElementById(“myIframe”);; We Adjust iframe height onload event by:
Read more >
How to make iFrames auto-resize to 100% height based on ...
How to make iFrames auto-resize to 100% height based on content · Go to the template you use most often to render your...
Read more >
How to adjust an iframe element's height to fit its content
In some cases JavaScript can be used to resize an iframe element to make it as tall as its content, making it look...
Read more >
Resize Iframe to Fit Content (Same Domain Only) - CSS-Tricks
Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found