How to set the iframe content of a React component?

Sometimes, we want to set the iframe content of a React component.

In this article, we’ll look at how to set the iframe content of a React component.

How to set the iframe content of a React component?

To set the iframe content of a React component, we use the createPortal function.

For instance, we write

import React, { useState } from "react";
import { createPortal } from "react-dom";

export const IFrame = ({ children, ...props }) => {
  const [contentRef, setContentRef] = useState(null);
  const mountNode = contentRef?.contentWindow?.document?.body;

  return (
    <iframe {...props} ref={setContentRef}>
      {mountNode && createPortal(children, mountNode)}
    </iframe>
  );
};

to assign the setContentRef ref to the iframe.

Then we call createPortal with children and the iframe’s body element with contentRef?.contentWindow?.document?.body to populate it.

Conclusion

To set the iframe content of a React component, we use the createPortal function.