Adding Functionality

Create and use a delete function in React using Python.

Adding a delete button

Currently, we can add items to the list, but what if we want to delete an item? Let’s add that functionality now.

Handling delete

To delete an item from the list, we create the handleDelete() function in line 18, which takes the item’s name to delete as a passed-in parameter. We then follow the pattern we used when we added the item, starting off by making a copy of our listItems state variable.

Note: We want to treat our state variables as immutable, and we should never modify them directly.

Next, in line 20 we remove the item of interest from the local copy of the Python list based on the name that was passed in. Then we call the setListItems() update function in line 21, passing in the local copy of our list that now has the specified item removed. This updates the overall state of the App component and triggers React to re-render the UI.

Since our list will have a “Delete” button for every item in the list, we’ll want to make each one specific to that particular item in the list. By using a Python lambda function instead of calling the handleDelete() function directly, we can actually save the value of the current list item inside the function that we attach to the onClick event handler at the time the list element gets created.

Rather than creating all of the list elements in one function, we break out the creation of a single list item element into its own React component:

Get hands-on with 1400+ tech skills courses.