title: How can I run React with hooks in an iFrame
body: <p>I am writing a React application in which I would like to dynamically render React components through an iFrame. I have a code editor on the webpage that allows users to write their React code, and I would like it to render that code into an iFrame embedded on the page.</p>
  <p>This html (stored in htmlString) is passed directly into the iFrame through the its srcdoc.</p>
  <pre><code>
  &lt;!DOCTYPE HTML&gt;
      &lt;html lang=&quot;en&quot;&gt;
       &lt;head&gt; 
        &lt;meta charset=&quot;utf-8&quot;&gt;
        &lt;title&gt;My New Snippet&lt;/title&gt;
      &lt;/head&gt;
      
      &lt;body&gt;
        &lt;div id=&quot;app&quot;&gt; &lt;/div&gt;
      
        &lt;script src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot; crossorigin&gt;&lt;/script&gt;
        &lt;script src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot; crossorigin&gt;&lt;/script&gt;
        &lt;script type=&quot;application/javascript&quot; src=&quot;https://unpkg.com/babel-standalone@6.26.0/babel.js&quot;&gt;&lt;/script&gt;
        &lt;script defer type=&quot;text/babel&quot;&gt;
          console.log(React);
          const { useState } = React
      
          const App = (props) =&gt; { 
            const [text, setText] = useState('hello');
      
            return (
              &lt;div&gt;
                &lt;h1&gt;{text}&lt;/h1&gt;
                &lt;input type=&quot;text&quot; value={text} onChange={(e) =&gt; setText(e.target.value)} /&gt;
              &lt;/div&gt;
            );
          }
      
          ReactDOM.render(
            App(),
          document.getElementById('app')
          );
      
        &lt;/script&gt;
      &lt;/body&gt; 
    &lt;/html&gt;
  
  </code></pre>
  <p>This is what the iFrame looks like in the render section of my component:</p>
  <pre><code>
  &lt;iframe
    srcDoc={htmlString}
    width=&quot;100%&quot;
    height=&quot;100%&quot;
    title=&quot;output&quot;
    sandbox=&quot;allow-scripts&quot;
  /&gt;
  
  </code></pre>
  <p>When running the code, I get the following error:</p>
  <pre><code>
  Uncaught TypeError: Cannot read properties of null (reading 'useState')
      at useState (react.development.js:1610:23)
      at App (&lt;anonymous&gt;:12:19)
      at &lt;anonymous&gt;:31:17
      at run (babel.js:61531:11)
      at check (babel.js:61597:10)
      at loadScripts (babel.js:61638:4)
      at runScripts (babel.js:61668:4)
      at transformScriptTags (babel.js:336:40)
      at babel.js:327:13
  
  </code></pre>
  <p>To me, this looks like React is not defined in the context, but through console.logs, I was able to confirm that it does exist in the correct scope.</p>