Announcing Dash Bio 1.0.0 🎉 : a one-stop-shop for bioinformatics and drug development visualizations.

ListGroup Callback - Possible?

Hi guys,

Was wondering if its possible to have a callback on a list group (generated dynamically) and know which ListGroupItem was clicked.

For example,


list_group = dbc.ListGroup(
    [
        dbc.ListGroupItem("Item 2", action=True),
        dbc.ListGroupItem("Item 2", action=True),
        dbc.ListGroupItem("Item 3", action=True"),
    ],
    id="list-group",
)

Hi,

Here’s one possible approach using pattern-matching callbacks and callback_context:


listgroup = dbc.ListGroup(
    [
        dbc.ListGroupItem(
            f"Item {i}", 
            id={"type": "list-group-item", "index": i}, 
            action=True
        )
        for i in range(3)
    ],
    id="list-group",
)

app.layout = html.Div(
    [
        listgroup,
        html.Div(id="test")
    ]
)

@app.callback(
    Output("test", "children"),
    Input({'type': 'list-group-item', 'index': ALL}, 'n_clicks'),  # from dash import ALL  # in v2
    State("list-group", "children"),
    prevent_initial_call=True
)
def update(n_clicks_list, children):
    # from dash import callback_context  # in v2
    clicked_id = callback_context.triggered[0]["prop_id"]
    # Parsing it 
    clicked_id = int(json.loads(clicked_id.split(".")[0])["index"])

    return f"Clicked on {children[clicked_id]}"

I adapted from an old example where I showed how the props in the specific child being clicked are available via State, but you might not need it…

1 Like

Great…that will do the job.

Is there a way to make the listgrouptitem active depending on which one was clicked?

I guess you can pass Output({'type': 'list-group-item', 'index': ALL}, 'active') and return a list of booleans where the index clicked_id is True and the rest False.

Thanks mate… I’ll look into it