What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js

Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scrollbars visible. Is there a way to remove the outer scrollbar and dynamically adjust the height of the HTML content to show only one scrollbar if needed?

Thank you!

import React, { useEffect } from "react";
import clsx from "clsx";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import CssBaseline from "@material-ui/core/CssBaseline";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import Paper from "@material-ui/core/Paper";

const drawerWidth = 240; 

Answer №1

To ensure that the content fits properly within the outer div, adjust it vertically outside the iframe. You can try reducing the vh of the outer div for a better fit. Once the outer div is adjusted correctly to fit vertically, the outer scrollbar will disappear.

If you wish to hide the outer scrollbar forcefully, you can refer to this link

Answer №2

To solve this issue easily, adjust the full screen height for div#root by setting it to

style={{ height: "100vh" }}
and update the parent's height for the iframe as follows:

  <Paper elevation={1} style={{ height: "90%" }} flex={1} overflow="auto">
    <iframe
      id="widget"
      name="widget"
      title="widget"
      ...

You can view the codesandbox example through this link:

https://codesandbox.io/s/material-demo-forked-2gtyz?fontsize=14&hidenavigation=1&theme=dark

Answer №3

An iframe is unable to resize itself autonomously in order to prevent advertisers from enlarging their ads on web pages without permission.

Therefore, it is the responsibility of the parent element to determine and set the height of an iframe. One way to achieve this is by directly reading the content's height within the iframe and adjusting its height accordingly with the following approach:

const iframeRef = React.createRef();
const [iframeHeight, setIframeHeight] = React.useState('100%');

React.useEffect(() => {
  setIframeHeight(`${iframeRef.current.contentWindow.document.documentElement.scrollHeight}px`);
}, []);

const iframeRef = React.createRef();

<iframe
  ref={iframeRef}
  id="widget"
  name="widget"
  title="widget"
  scrolling="yes"
  frameBorder="0"
  width="100%"
  height={iframeHeight}
  srcdoc={html}
  style={{ position: "relative", height: iframeHeight }}
></iframe>

If the height of the iframe is subject to change due to asynchronous operations or user interactions, messages must be sent from the iframe to its parent using Window.postMessage when the height changes. These messages should include the updated height. Subsequently, an event listener for the message event needs to be added to the parent element to adjust the iframe's height accordingly.

Answer №4

When generating the HTML code, make sure to make adjustments in the <script> tag by adding the resizeIframe function and calling that function at the end of the document ready event:

        <script>
          function resizeIframe()
          {
            var document = window.parent.document;
            var iframe = document.getElementById('widget');
            iframe.style.height = (iframe.contentWindow.document.documentElement.scrollHeight + 18) + 'px';
          }

          var my_jquery = $.noConflict(true);
          my_jquery(document).ready(function(){
            my_jquery('#jEZeucEZQISp').DataTable({
              data: [["Alabama","Montgomery","https://en.wikipedia.org/wiki/Montgomery,_Alabama","TRUE"],["Alaska","Juneau","https://en.wikipedia.org/wiki/Juneau,_Alaska","TRUE"], ...],
              iDisplayLength:  25 ,
              "scrollX":      true,
              scrollY:        '',
              scrollCollapse:  false ,
              search: {
                search: "",
              },
            });
            resizeIframe();
            my_jquery(window.parent).on('resize', resizeIframe);
          });
        </script>

Afterwards, update your <IFRAME> tag as follows:

          <iframe
            id="widget"
            name="widget"
            title="widget"
            scrolling="auto"
            frameBorder="0"
            width="100%"
            srcDoc={html}
            style={{ position: "relative"}}
          ></iframe>

Check it on sandbox

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 TableHeader component in Material UI does not apply bold styling to its content

I am currently working on developing a table using Material UI. The documentation specifies that the TableHeader component should automatically make the text inside bold, however, I am facing an issue where this is not happening in my project. It's im ...

Troubleshooting: Why is my Local Image not displaying in ReactJS

I am facing an issue with displaying images in my React application using an array of image paths. Below is the code snippet I have written: import React, { Component } from 'react'; class ItemsList extends Component { constructor() { ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

"ReactJS error: Unable to upload file due to a 400

Every time I attempt to upload a file, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 404". I'm puzzled as to why this is happening. Here's the section of my code that seems to be causing the issue. ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

Ways to identify input that has been altered dynamically

I'm currently trying to figure out why I can't seem to detect any input changes with the code snippet below: $("#fname").on("change", function () { console.log("The text has been changed."); }); $("button").o ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

QML: Inside and outside styling attributes

Within my QML Text (RichText) elements, I have incorporated multiple CSS-styled html elements using the inline 'style' attribute within each tag (e.g. <code style=\"background-color:black; text-indent: 10px\"></code&g ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

How to toggle a specific element in Bootstrap 4 with a single click, without affecting other elements

I've been struggling with a frustrating issue: I have 3 elements next to each other at the bottom of the fixed page. I tried using Bootstrap4 toggles to display only text when a user clicks on an image, but it ends up toggling all the images instead o ...

Is there a way for me to retrieve props that have been passed through the Vue router within a Vue component?

I have configured a route as shown below: { path: 'fit-details', name: 'fit-details', component: Fitment, props: true }, I am passing props via the route using data from the state: this.$router.push({ path: 'fit-details&a ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow. ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

Encountering an issue with an Uncaught SyntaxError: Unexpected identifier

I've been attempting to send data through ajax but keep encountering errors. Here's the code I have: jQuery.ajax({ url : '', type: 'POST', ...

Customizing Bootstrap modal backdrop with CSS

I'm exploring how to achieve the backdrop effect of the Bootstrap modal without actually having to load a modal. However, I'm struggling to make it work correctly. Can anyone provide insight into the CSS that the Bootstrap backdrop utilizes inter ...

Can anyone provide guidance on uploading data to a mongodb database? I've attempted a few methods but keep encountering errors

const info = { name, price, quantity, image, desc, sup_name, email } fetch('https://gentle-plateau-90897.herokuapp.com/fruits', { method: 'POST', headers: { 'content-type': 'application/jso ...

React - useState is not working as expected in setting the initial value

Currently, I'm in the process of refactoring my code to incorporate Hooks and have encountered a perplexing obstacle My functional component looks like this: export const MakeComponent = props => { const { path, value, info, update } = props; ...