Search⌘ K
AI Features

Handling Input

Explore managing controlled text inputs in React using Transcrypt. Understand how to update state with handleChange, link labels to inputs, and submit data with alerts, all while keeping code in Python.

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. ...