Search⌘ K
AI Features

Adding More Functionality

Explore how to implement editing capabilities within React components using Python and Transcrypt. Understand managing state variables like editItem, using Python ternary expressions for conditional rendering, and handling common issues with Python-JavaScript truthiness differences to build an efficient, user-friendly front-end.

Now that we can add and remove items from our list, let’s also add the ability to edit items in the list. Here’s the updated code to do so.

# 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
Adding editable list items

Handling edits

To handle edits, we reuse the text input box we already have. To do this, we need a way of knowing whether we are adding a new value to the list or editing an existing value. To accomplish this, we created a new state variable editItem at line 5 that is either an empty string or holds the original value of the item being edited. This allows us to do two things. First, when we submit the form if the value is an empty string, then we know we need to add a value. Second, if there is a non-empty value, we use that original value to look up which list item needs to be changed.

Python’s ternary expression

In line 52 ...