React in python (Pyodide)

4/22/2019

Pyodide is a new project from Mozilla. It aims to bring python into the browser, making use of WebAssembly. You can read the full blog post at https://hacks.mozilla.org/2019/04/pyodide-bringing-the-scientific-python-stack-to-the-browser/.

I wanted to try it out, and see how easy it would be run python in the browser, while also being able to interact with the DOM, as I would normally do in javascript. Turns out, Pyodide makes this really simple. Pyodide will proxy javascript objects with their python counter parts, in a way that feels very seamless.

After I had got the project setup, I decided to have a go and running a small React application, written in Python. As React isn't actually dependant on JSX syntax, this is trivial to get running thanks to Pyodide. All React components just have to return React.createElement` calls instead (which babel would normally translate JSX code into).

The result:

from js import document, window

React = window.React
ReactDOM = window.ReactDOM


def HelloWorldReactComponent():
    return React.createElement(
        "div", {"style": {"display": "flex"}},
        "Hello world. This was rendered with React."
    )


ReactDOM.render(HelloWorldReactComponent(), document.querySelector("#result"))

You can see a live demo at: https://amwam-pyodide-testing.now.sh or alternatively the code at: https://github.com/Amwam/pyodide-testing-playground