chillingfox
chillingfox

Reputation: 141

How to get Pyodide to work in a React component?

I am trying to make my own Python fundamentals tutorial that's similar to the interactive editor that codecademy.com has. However, I'm struggling to make Pyodide work with React.

Using the very basic getting started example, I can make the following work in index.html of my create-react-app app:

<!-- PYODIDE -->
  <script src="https://cdn.jsdelivr.net/pyodide/dev/full/pyodide.js"></script>

  <title>React App</title>
</head>

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
  <script type="text/javascript">
    async function main() {
      let pyodide = await loadPyodide();
      console.log(pyodide.runPython(`
          import sys
          sys.version
      `));
      pyodide.runPython("print(1 + 2)");
    }
    main();
  </script>

.....

</body>

However, when I try to move the same code into a separate component, it says 'loadPyodide' is not defined

import React from 'react'

const Task1 = ({ replNum, task }) => {

    async function main() {
        let pyodide = await loadPyodide();
        console.log(pyodide.runPython(`
            import sys
            sys.version
        `));
        pyodide.runPython("print(1 + 2)");
    }
    main();


    return ( 
            SOME CODE
)

Why is this?

Upvotes: 1

Views: 1538

Answers (1)

Nikolay
Nikolay

Reputation: 12245

Try using window.loadPyodide instead of loadPyodide. React uses modules where 'use strict' is set, so undeclared global variables are not allowed.

Upvotes: 2

Related Questions