/* eslint-disable jsx-a11y/iframe-has-title */
import { useRef, useEffect } from 'react';
import reset from './styleReset';
const IFrame = function IFrame(props) {
  const {
    code,
    active,
    className
  } = props;
  const self = useRef();
  useEffect(() => {
    const iframe = self.current;
    if (iframe) {
      let html = '';
      if (active) {
        html = `
        <head>
          <style>${reset}</style>
        </head>
        <body>
          <div>${code}</div>
        </body>`;
      } else {
        html = `
        <head>
        </head>
        <body>
        </body>`;
      }
      iframe.contentWindow.document.open();
      iframe.contentWindow.document.write(html);
      iframe.contentWindow.document.close();
      const height = iframe.contentWindow.document.body.offsetHeight;
      iframe.style.height = `${height}px`;
    }
  }, [code, active]);
  return <iframe className={className} ref={self} frameBorder="0" />;
};
export default IFrame;