Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Pyscript in React?

I'm trying to use PyScript in NextJS, but I'm seeing several errors. I have no clue how to make a React component of PyScript. Has anyone successfully used PyScript in ReactJS? Thanks,

const Home: NextPage = () => {
  return (
    <div>
      <Head>
        <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
        <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      </Head>
      <div className="mx-auto container">
        <py-repl></py-repl>
        <py-script>
          import datetime as dt
          pyscript.write(‘today’, dt.date.today().strftime(‘%A %B %d, %Y’))
          def compute_pi(n):
              pi = 2
              for i in range(1,n):
                  pi *= 4 * i ** 2 / (4 * i ** 2 - 1)
              return pi
          pi = compute_pi(100000)
          pyscript.write(‘pi’, f’π is approximately {pi:.3f}’)
        </py-script>
      </div>
    </div>
  )
}

Error 1.

Type error: Property 'py-repl' does not exist on type 'JSX.IntrinsicElements'.

Error 2.

Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.
See more info here: https://nextjs.org/docs/messages/react-hydration-error

Error 3. The above <py-script> causes

JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in File "", line 129, in write AttributeError: 'NoneType' object has no attribute 'innerHTML' )
like image 737
Watanabe.N Avatar asked Aug 09 '26 08:08

Watanabe.N


1 Answers

you can set python script into dangerouslySetInnerHTML

<div
  dangerouslySetInnerHTML={{
    __html: `<py-script>
    from datetime import datetime
    now = datetime.now()
    now.strftime("%m/%d/%Y, %H:%M:%S")
    </py-script>`,
  }}
/>

Or

PyScript-React is not yet available, but you can follow it - https://github.com/Py4Js/PyScript-React

like image 85
gaozhidf Avatar answered Aug 10 '26 20:08

gaozhidf