The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150px tall Iframe with scrollbars.

Is there a way to adjust the height so that there are no scrollbars, and instead have the scrolling behavior controlled by the NextUI modal using scrollBehaviour:outside?

Code snippet for the Iframe component:

const IframeComponent = () => {
  return <iframe title="wheel" url="XXXX" className="h-full w-full rounded-[30px]" />
}

export default IframeComponent

Code snippet for the Modal component:

import { Modal, ModalBody, ModalContent, ModalProps, useDisclosure } from "@nextui-org/react"
import Image from "next/image"
import { useEffect, useState } from "react"
import IframeComponent from "./Iframe"

const IframeWrapper = () => {
  const { isOpen, onOpen, onClose, onOpenChange } = useDisclosure()
  const [scrollBehavior, _setScrollBehavior] = useState<ModalProps["scrollBehavior"]>("outside")

  // Open the modal on load.
  // Should the modal open automatically on each load?
  useEffect(() => {
    onOpen()
  }, [onOpen])

  return (
    <>
      <Modal
        isOpen={isOpen}
        onOpenChange={onOpenChange}
        size="5xl"
        placement="center"
        hideCloseButton={true}
        radius="lg"
        scrollBehavior={scrollBehavior}
        className="w-[90vw]"
      >
        <ModalContent>
          <>
            <ModalBody className="p-0">
              <button
                onClick={onClose}
                className="absolute right-4 top-3 select-none appearance-none rounded-full p-2 text-foreground-500 outline-none tap-highlight-transparent data-[focus-visible=true]:z-10 data-[focus-visible=true]:outline-2 data-[focus-visible=true]:outline-offset-2 data-[focus-visible=true]:outline-focus rtl:left-1 rtl:right-[unset] lg:right-10 lg:top-7"
              >
                <Image
                  src="/icons/closeModal.svg"
                  alt="close button"
                  width={0}
                  height={0}
                  className="h-8 w-8 lg:h-16 lg:w-16"
                />
              </button>
              <IframeComponent />
            </ModalBody>
          </>
        </ModalContent>
      </Modal>
    </>
  )
}
export default IframeWrapper

Answer №1

Resizing an iframe to match the size of its content may seem like a simple task, but in reality, it poses three distinct challenges.

Accurately determining the size of the content is the first hurdle. Modern browsers offer multiple methods for calculating this, each producing varying results that are not consistently accurate. In cases where the content does not exceed the body element, using

document.body.getClientRect().bottom
generally provides the most reliable answer.

The second challenge lies in detecting changes within the content to trigger a reassessment of its size. The ResizeObserver API can help with this when everything is contained within the body element. However, if the content extends beyond this scope, integrating the MutationObserver API becomes necessary.

Finally, passing the updated height from the iframe to the parent page is essential. This is where the PostMessage API proves invaluable.

If this process seems more complicated than anticipated, consider utilizing the comprehensive JS library I created called iframe-resizer. Additionally, there is a convenient React component available for seamless integration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The specific tag <labal> cannot be identified by this browser. To display a React component, ensure its name begins with a capital letter

Every time I try to utilize the tag in react, a warning pops up. Below is my code snippet and the warning message displayed: https://i.sstatic.net/DcHfB.png https://i.sstatic.net/vP8sr.png ...

Error Encountered: "fsevents is not defined" during ReactJS Test

I've been working on writing test cases for my program and I recently came across recommendations for testing-library/react and jest-junit. After installing both packages using npm as devDependencies and updating my test script to "test": 'react- ...

Upon being provided with a route param, the response will be

For my current project using Express, I want to implement Reddit-like functionality where appending ".json" to any URL will return JSON data instead of the rendered template. To set up the rendering engine in Express, I am using Jade. Here is how I config ...

I am looking for a custom script for a splash page that will automatically redirect users to one of three designated pages based on the information stored

As a programmer, I'm well-versed in coding but lack knowledge about creating and utilizing cookies. If anyone could provide guidance on this matter, it would be highly appreciated. I believe I require two concise scripts for this task. 1st Script: T ...

Storing chosen choices from various select lists with similar class name in JavaScript

I am struggling to save all the selected options in an array for future output. Despite trying various suggestions, I haven't been able to make it work yet. The class names and names cannot be modified. HTML <select class="addon addon-select" nam ...

How to add additional text after a particular line within a string containing multiple lines using JavaScript

What is the best way to add a new string after line 2 in a multi-line JavaScript string? ...

What is the best way to input data into nedb across various lines?

There is a requirement to store each element of an array into separate lines while saving it in the NEDB database. The idea is to add "\r\n" after every element, like this: Currently, I am doing the following: usernames = ["name1","name2","name3 ...

Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows: module.exports = { css: { loaderOptions: { scss: { additionalData: `@import "@/st ...

What could be causing my webpage content to be partially hidden by my CSS menu?

I am currently working on my website which features a CSS menu with my website logo, a text box, and a dropdown. Additionally, I have created a login form using a table like the one shown below. <p>&nbsp;</p><table width="40%" border="0 ...

unit test confirming event listener removed

Currently learning jest and enzyme to test react apps that are bootstrapped with create-react-app. Encountering issues when mocking add/removeEventListener crashes using unmount after using shallow, while warning is displayed when using unmount after moun ...

Using Google Chart API to create stacked bar charts with annotations using symbols

I am trying to annotate the bars in my stacked bar chart with currency symbols for profit and costs. While I have been able to successfully annotate the bars without currency symbols, I am facing difficulties in displaying them with the $ prefix. Can anyo ...

Challenge with Hovering within Cufon Elements

When utilizing multiple lists and hover states, the parent Cufon style takes over the child. For instance, in the scenario below, when hovering over the Second Level link, it will switch to a different weight. Is there a setting I can adjust to keep the n ...

Ways to ensure ngModel is accessible across components

I've hit a wall and I'm starting to lose my mind. I've tried all the different methods like FormsModules, ReactiveForms, FORMDIRECTIVES, Input, Output, but I just can't seem to figure out how to make ngModel work between components. My ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

implement css property solely when device is in landscape orientation

I am facing an issue with applying CSS to a mobile device, specifically for horizontal orientation. When the device is in a vertical position, the page appears blank, and different CSS loads for desktop view. Although I have managed to make the desktop CS ...

Transforming API data into a particular type using Typescript

I am looking to extract only specific properties from a given object. Can TypeScript interfaces be used to iterate through the data and eliminate unnecessary properties? Sample data: [ 0: { "original_language" : "en", "t ...

Utilizing nested redux-forms to include a voucher form within a checkout form

I am currently working on developing a checkout page that includes a nested coupon code or voucher subform using redux-form. The checkout form will have options like Country selection, and within this form, I want to add a sub form for applying a Voucher. ...

Guide to incorporating the useEffect hook within a React Native View

I am trying to use useEffect within a return statement (inside a Text element nested inside multiple View elements), and my understanding is that I need to use "{...}" syntax to indicate that the code written is actual JavaScript. However, when I implement ...

Issue: Invalid element type detected: expected a string (for built-in components) or a class/function

Currently, I am in the process of learning how to make API calls using React Redux. I decided to practice by implementing an example in StackBlitz. However, I encountered an error after selecting a channel and clicking on the 'Top News' button. C ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...