Categories
React Answers

How to Set the Content of an Iframe of a React Component?

Spread the love

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

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

Set the Content of an Iframe of a React Component

To set the content of an iframe of a React component, we can set the srcDoc prop of the iframe element.

For instance, we can write:

import React from "react";

export default function App() {
  const myHTML = `<h1>Hello World</h1>`;
  return (
    <div>
      <iframe srcDoc={myHTML} title="hello" />
    </div>
  );
}

to set the srcDoc prop to the HTML string that we want to display as the iframe’s content.

Therefore, we should see ‘Hello World’ displayed inside the iframe.

Conclusion

To set the content of an iframe of a React component, we can set the srcDoc prop of the iframe element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *