Handling Input

Reactively taking input from the user with Transcrypt.

Running the code

The following code example pops up an alert in the web browser and displays the text that is entered when the “Submit” button is clicked. Press the “Run” button to start the widget below.

# Load React and ReactDOM JavaScript libraries into local namespace
React = require('react')
ReactDOM = require('react-dom')

# Map React javaScript objects to Python identifiers
createElement = React.createElement
useState = React.useState


def render(root_component, props, container):
    def main():
        ReactDOM.render(
            React.createElement(root_component, props),
            document.getElementById(container)
        )

    document.addEventListener('DOMContentLoaded', main)


# JavaScript function mappings
alert = window.alert
Updated code which takes input reactively.

Explaining the changes

Other than renaming a few things, the HTML file and our pyreact.py JavaScript wrapper module haven’t really changed much from what we had in the previous section. We did add a JavaScript function mapping for window.alert() in line 21 to the pyreact.py module for convenience and to keep all of the JavaScript calls in one Python module. To break down our app.py module, we start with a few imports from the module where we did our mapping of JavaScript functions to Python objects. By using this pattern, we keep the bulk of our application written completely in Python and avoid mixing programming languages that make the Python linter complain.

As in previous examples, we have one React component named App. It is the entry point for the render() function that inserts our dynamically created elements into the DOM. The important part of the App function is that the return value is a React element type. In lines 14-22, we are ...