10 min read

Responsive Iframe Components in React: Best Practices

Shashank Dubey
Content & Marketing, Wbcom Designs · Published Dec 26, 2023 · Updated Nov 15, 2026
_Responsive Iframe Components in React

Iframes remain one of the most practical ways to embed external content in a web application, whether that is a YouTube video, a payment form, a map widget or a third-party app. The embedded page runs in its own browsing context, which keeps its code separate from yours. In React, a good iframe component handles sizing, lazy loading, messaging, accessibility and failure states. This guide covers each of those with code, and with WordPress headless front ends in mind. It is based on MDN’s documentation for the iframe element, CSS aspect-ratio, window.postMessage and CSP frame-ancestors.

Quick answer: To make an iframe responsive in React, wrap it in a container with width 100% and a CSS aspect-ratio such as 16 / 9, and do not hard-code a pixel height. Add loading=”lazy”, a descriptive title, a restrictive sandbox, and check event.origin on every postMessage you receive.

Last updated: 15 November 2026

Understanding Iframes in React

An iframe (inline frame) is an HTML element that embeds a separate HTML document within the current page. In React it works like any other element, but the content inside lives in a separate browsing context with its own DOM, styles and JavaScript scope, so your components and CSS cannot reach into it.

Typical uses are videos from YouTube or Vimeo, payment forms, maps, dashboards and forms from services like Typeform or Google Forms. For WordPress developers building headless front ends with React, iframes are often the practical way to embed legacy widgets or third-party tools that have no React component.

The key challenge is making them responsive. A fixed-width iframe overflows on phones, and an iframe that loads late can shift your layout. A badly configured one can also load more than it should or expose your page to untrusted content. The practices below address each of these.

Best Practices for Responsive Iframe Components

1. Size the Iframe With CSS aspect-ratio

The most reliable way to keep an embed proportional is to let CSS hold the shape. The aspect-ratio property is, per MDN, widely available across browsers since September 2021. Set the width to 100% and give the iframe a ratio instead of a fixed height.

.iframe-container {
  width: 100%;
  max-width: 1200px;
  margin-inline: auto;
}

.iframe-container iframe {
  display: block;
  width: 100%;
  aspect-ratio: 16 / 9;
  border: 0;
}

Because the browser reserves the box before the embed loads, the layout does not jump when the content arrives, which helps Cumulative Layout Shift. Change the ratio for other content: 4 / 3 for older video, 1 / 1 for a square widget. If you must support very old browsers, the older padding-bottom trick (56.25% for 16:9, or height / width * 100 for any ratio) still works, but you rarely need it now.

function ResponsiveIframe({ src, title, ratio = '16 / 9' }) {
  return (
    <div className="iframe-container">
      <iframe
        src={src}
        title={title}
        style={{ aspectRatio: ratio }}
        loading="lazy"
        referrerPolicy="strict-origin-when-cross-origin"
      />
    </div>
  );
}

2. Use State for Content Changes, Not for Sizing

React state is the right tool when the embed itself should change with the viewport, for example loading a compact version of a widget on small screens. For plain sizing, CSS is simpler and does not re-render. Use window.matchMedia rather than a resize listener, so the component updates only when the breakpoint is crossed.

import { useState, useEffect } from 'react';

function AdaptiveIframe({ desktopSrc, mobileSrc, title }) {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const query = window.matchMedia('(max-width: 768px)');
    const update = () => setIsMobile(query.matches);
    update();
    query.addEventListener('change', update);
    return () => query.removeEventListener('change', update);
  }, []);

  return (
    <iframe
      src={isMobile ? mobileSrc : desktopSrc}
      title={title}
      style={{ width: '100%', aspectRatio: isMobile ? '4 / 3' : '16 / 9', border: 0 }}
    />
  );
}

In a server-rendered or headless setup, the initial state is false on the server, so the desktop source renders first and switches after hydration. If that flash matters, pick one source and let CSS handle the rest.

3. Implement CSS Media Queries for the Surrounding Layout

Beyond the iframe itself, the layout around it needs to adapt. Use media queries to adjust container padding and, where a different shape reads better on a phone, the ratio.

.iframe-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

@media screen and (max-width: 768px) {
  .iframe-wrapper { padding: 0 10px; }
  .iframe-container iframe { aspect-ratio: 4 / 3; }
}

@media screen and (max-width: 480px) {
  .iframe-container iframe { aspect-ratio: 1 / 1; }
}

This layered approach keeps embedded content readable on desktops, tablets and phones. For WordPress theme developers building React-based front ends, these patterns sit comfortably alongside responsive page builder layouts.

4. Handle Cross-Domain Communication Safely

When the iframe loads a page from a different origin, the same-origin policy blocks direct DOM access in both directions. The postMessage API is the supported channel. MDN’s guidance is to always verify the sender’s identity through event.origin (and event.source where you know the window), and then still validate the shape of the data, because a trusted site can itself be compromised.

import { useEffect, useRef } from 'react';

const TRUSTED_ORIGIN = 'https://trusted-domain.com';

function SecureIframe({ onHeight, height }) {
  const frameRef = useRef(null);

  useEffect(() => {
    function handleMessage(event) {
      if (event.origin !== TRUSTED_ORIGIN) return;
      if (event.source !== frameRef.current?.contentWindow) return;

      const { type, height } = event.data ?? {};
      if (type === 'RESIZE' && Number.isFinite(height)) {
        onHeight(height);
      }
    }
    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [onHeight]);

  function sendConfig() {
    // Always pass an exact targetOrigin, never '*'
    frameRef.current?.contentWindow?.postMessage(
      { type: 'CONFIG', theme: 'light' },
      TRUSTED_ORIGIN
    );
  }

  return (
    <iframe
      ref={frameRef}
      src={`${TRUSTED_ORIGIN}/widget`}
      title="Trusted widget"
      sandbox="allow-scripts allow-forms"
      onLoad={sendConfig}
      style={{ width: '100%', height: height ?? 400, border: 0 }}
    />
  );
}

Two details matter here. First, when you send, MDN says to always provide a specific targetOrigin rather than “*”, so a page that navigates away cannot intercept the message. Second, the sandbox above omits allow-same-origin on purpose: MDN strongly discourages combining allow-scripts and allow-same-origin for same-origin content, because the embedded page could then remove its own sandbox. If the embed needs its cookies or storage, you must add allow-same-origin, so only do that for providers you trust.

5. Optimize Performance With Lazy Loading

Each iframe creates a separate browsing context, loads its own resources and may run its own scripts. Several eager iframes slow the page and can hurt Core Web Vitals. The simplest fix is the native loading attribute, which per MDN defers loading until the frame nears the viewport. MDN also notes that deferral only happens when JavaScript is enabled.

function LazyIframe({ src, title }) {
  return (
    <iframe
      src={src}
      title={title}
      loading="lazy"
      style={{ width: '100%', aspectRatio: '16 / 9', border: 0 }}
    />
  );
}

For more control, such as showing a poster image until the visitor scrolls to the embed, use the Intersection Observer API.

import { useState, useRef, useEffect } from 'react';

function IntersectionIframe({ src, title }) {
  const [isVisible, setIsVisible] = useState(false);
  const containerRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setIsVisible(true); },
      { rootMargin: '200px' }
    );
    if (containerRef.current) observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, []);

  return (
    <div ref={containerRef} style={{ aspectRatio: '16 / 9' }}>
      {isVisible && (
        <iframe src={src} title={title} style={{ width: '100%', height: '100%', border: 0 }} />
      )}
    </div>
  );
}

The rootMargin of 200px starts loading just before the embed scrolls into view. This matters most on WordPress sites with several embeds, where each extra iframe adds to the performance impact.

6. Resize to the Embed’s Content, Not Just the Window

Listening to window resize events only tells you the viewport changed, not what the embed needs. If the embedded page controls its own height (a form that grows with validation messages, for example), have it post its height to the parent and apply it, using the verified handler from practice 4. This only works when you control or can configure the embedded page.

import { useState } from 'react';

function AutoHeightIframe() {
  const [height, setHeight] = useState(400);

  // SecureIframe from practice 4 verifies origin and source before calling onHeight
  return <SecureIframe onHeight={setHeight} height={height} />;
}

If the embed cannot message you, keep the aspect-ratio approach and accept an internal scrollbar rather than guessing a height. Where you do need a JavaScript resize handler, debounce it, since a handler that sets state on every pixel of resizing causes needless re-renders.

7. Add Proper Accessibility Attributes

Every iframe needs a concise title that describes its content. MDN notes that screen reader users rely on the title to label the frame, and without it they have to navigate into the frame to find out what it contains. A separate aria-label is not needed when a good title is present, and a tabIndex is not needed because iframes are focusable by default.

<iframe
  src="https://example.com/form"
  title="Contact form: send us your enquiry"
  sandbox="allow-forms allow-scripts"
/>

For WordPress sites aiming at WCAG conformance, a missing frame title is a common failure and an easy one to prevent in a shared component: make title a required prop. Making your website SEO friendly also overlaps with accessibility, since both reward well-structured content.

8. Implement Fallbacks for Failed Embeds

External content can fail because of network problems, a changed URL, or a policy that forbids framing. The tempting fix is an onError handler, but MDN states that user agents do not fire the error event on iframes, and that the load event fires even if the content fails to load.

A practical approach is to give every embed a visible alternative: a link that opens the content in a new tab, shown beside or under the frame. You can also show a fallback after a timeout if the embed never signals that it is ready, which works when you control the embedded page and it sends a ready message.

import { useState, useEffect, useRef } from 'react';

function IframeWithFallback({ src, title, origin, readyTimeout = 8000 }) {
  const frameRef = useRef(null);
  const [ready, setReady] = useState(false);
  const [timedOut, setTimedOut] = useState(false);

  useEffect(() => {
    const id = setTimeout(() => setTimedOut(true), readyTimeout);
    function onMessage(event) {
      if (event.origin !== origin) return;
      if (event.source !== frameRef.current?.contentWindow) return;
      if (event.data?.type === 'READY') setReady(true);
    }
    window.addEventListener('message', onMessage);
    return () => {
      clearTimeout(id);
      window.removeEventListener('message', onMessage);
    };
  }, [origin, readyTimeout]);

  return (
    <div>
      <iframe ref={frameRef} src={src} title={title} style={{ width: '100%', aspectRatio: '16 / 9', border: 0 }} />
      {!ready && timedOut && (
        <p>
          This content is slow to load. <a href={src} target="_blank" rel="noopener noreferrer">Open it in a new tab</a>.
        </p>
      )}
    </div>
  );
}

Security Considerations

Iframes introduce security surfaces that must be managed carefully:

  • Use the sandbox attribute: MDN describes sandbox as a way to restrict what the embedded page can do. Start with an empty sandbox and add only the permissions you need, and avoid combining allow-scripts with allow-same-origin for same-origin content.
  • Use the allow attribute: It sets a Permissions Policy for the frame, so a video embed does not get camera or microphone access by default.
  • Control referrers: The default referrer policy is strict-origin-when-cross-origin; avoid unsafe-url, which MDN says leaks origins and paths from secure pages to insecure ones.
  • Set Content-Security-Policy headers correctly: frame-src controls where your page may load frames from, while frame-ancestors controls who may embed your page. Per MDN, frame-ancestors does not fall back to default-src and is not supported in a meta element, so send it as an HTTP header. X-Frame-Options is the older equivalent.
  • Validate postMessage origins and data: Never process messages from unverified origins, and check the structure of what you receive.
  • Avoid embedding untrusted content: Only embed content from providers you trust.

Summary

Responsive iframe components in React come down to a few habits: let CSS aspect-ratio hold the shape, lazy load what is below the fold, verify every postMessage, give each frame a descriptive title, and plan a visible fallback rather than relying on an error event that never fires. Whether you are building a React-based WordPress frontend or a standalone application, these patterns form a solid base for production embeds.

Frequently asked questions

How do I make an iframe responsive in React?

Wrap the iframe in a container, set its width to 100% and give it a CSS aspect-ratio such as 16 / 9 instead of a fixed pixel height. The browser keeps the proportions at any screen width.

Does onError work on an iframe in React?

No, not for load failures. MDN says browsers do not fire the error event on iframes and that the load event fires even when the content fails. Use a visible fallback link and, if you control the embed, a ready message with a timeout.

Is loading=”lazy” supported on iframes?

Yes. The loading attribute on iframes defers loading until the frame is near the viewport, according to MDN. It only defers when JavaScript is enabled, so keep embeds below the fold lazy and above-the-fold ones eager.

Is it safe to use sandbox with allow-scripts and allow-same-origin?

Not for same-origin content. MDN strongly discourages combining them because the embedded page can then remove the sandbox attribute. For third-party origins, prefer allow-scripts alone and add only the permissions the embed needs.

How do I let an iframe tell React its height?

Have the embedded page call window.parent.postMessage with its height and an exact target origin. In React, listen for message events, check event.origin and event.source, validate the number, and set it in state.

Interesting Reads:

How to Embed a YouTube Playlist in WordPress

10 Essential Tools For Front End Developers

Shashank Dubey
Content & Marketing, Wbcom Designs

Shashank Dubey, a contributor of Wbcom Designs is a blogger and a digital marketer. He writes articles associated with different niches such as WordPress, SEO, Marketing, CMS, Web Design, and Development, and many more.

Related reading