How to prevent reloading of iframe in react.js?

Member

by rollin , in category: Javascript , a month ago

How to prevent reloading of iframe in react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , a month ago

@rollin 

To prevent reloading of an iframe in React.js, you can set the src attribute of the iframe to an empty string when the component containing the iframe is unmounted. This will prevent the iframe from loading content again when the component is re-mounted.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import React, { useEffect } from 'react';

const MyComponent = () => {

  useEffect(() => {
    return () => {
      // Set the src attribute of the iframe to an empty string on unmount
      document.getElementById('myIframe').src = '';
    };
  }, []);

  return (
    <iframe id="myIframe" src="https://example.com"></iframe>
  );
};

export default MyComponent;


In the above example, the src attribute of the iframe is set to an empty string when the component is unmounted using the useEffect hook with an empty dependency array. This will prevent the iframe from reloading its content when the component is re-mounted.