Multi-select list

Hi everyone! I am brand new to Dash, and currently testing out its functionality to see if it will work for my planned project. So far I am pretty convinced that it will.

Right now I am trying to figure out how to make a multi-select list. The idea is to have a dynamically created list in a sidebar that is created based on filter values, and that I should be able to toggle on and off the different entries. The entries are linked to datasets that will decide what is plotted in a graph in the main area of the dashboard. So far I’ve only found a multi-select feature in a dropdown menu, but I would like for it to be styled in a similar manner to dbc.ListGroup.

Here is an example that I found here that nearly gets me there, but it toggles off every other item when selected. I basically just want it to toggle active between True/False and then update the graph with the current state of the list whenever there is a change.


from dash import html, dcc, callback, Input, Output, ALL, State, callback_context
import dash_bootstrap_components as dbc
import json

list_group = html.Div(
    [
        dbc.Label("Data Selector", html_for="input-data-selector"),
        dbc.ListGroup([
            dbc.ListGroupItem(name, active=False, action=True, id={"type": "list-group-item", "index": i})
            for i, name in enumerate([
                "Item 1",
                "Item 2",
                "Item 3",
                "Item 4"
            ])],
        )
    ],
    id="input-data-selector",
    className="mb-3",
)

@callback(
    Output({'type': 'list-group-item', 'index': ALL}, 'active'),
    Input({'type': 'list-group-item', 'index': ALL}, 'n_clicks'),  # from dash import ALL  # in v2
    State("input-data-selector", "children"),
    prevent_initial_call=False
)
def update(n_clicks_list, children):
    clicked_id = callback_context.triggered[0]["prop_id"]
    clicked_id = json.loads(clicked_id.split(".")[0])["index"]
    return [clicked_id == i for i in range(len(n_clicks_list))]

dbc.Checklist is one option for doing this: Input - dbc docs

2 Likes

Thanks - I have not yet implemented it, but the related Switches seems also to do what I want (looking a little more appealing than the regular checkboxes). Marked as solved!