Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Render Lists #1061

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open

Conversation

dgodinez-dh
Copy link
Contributor

@dgodinez-dh dgodinez-dh commented Dec 12, 2024

plugins/ui/docs/describing/render_lists.md Outdated Show resolved Hide resolved
my_content_list = content_list(food)
```

## Filter lists of items
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're missing talking about the key prop here. Each value in the list should have a key, and the React docs go into explicitly: https://react.dev/learn/rendering-lists#why-does-react-need-keys

In terms of deephaven.ui, it can be observed why you need keys when running a todo app. See an example without keys: #731

If you comment out the key=str(i) line, you'll see it screws up if you delete any of the cells except the last one; it will always "delete" the last cell:

from deephaven import ui
import itertools


@ui.component
def ui_cell(label="Cell"):
    text, set_text = ui.use_state("")

    return ui.text_field(label=label, value=text, on_change=set_text)


@ui.component
def ui_cells():
    id_iter, set_id_iter = ui.use_state(lambda: itertools.count())
    cells, set_cells = ui.use_state(lambda: [next(id_iter)])

    def add_cell():
        set_cells(lambda old_cells: old_cells + [next(id_iter)])

    def delete_cell(delete_id: int):
        set_cells(lambda old_cells: [c for c in old_cells if c != delete_id])

    return ui.view(
        list(
            map(
                lambda i: ui.flex(
                    ui_cell(label=f"Cell {i}"),
                    ui.action_button(
                        ui.icon("vsTrash"),
                        aria_label="Delete cell",
                        on_press=lambda: delete_cell(i),
                    ),
                    align_items="end",
                    # key=str(i),
                ),
                cells,
            )
        ),
        ui.action_button(ui.icon("vsAdd"), "Add cell", on_press=add_cell),
        overflow="auto",
    )


cells = ui_cells()

By adding the key, it knows how to track the elements and delete the correct one.

Should also write it with list comprehension, and possibly refactor the child todo component into a ui_deletable_cell or something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants