✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Multiple modals: a use case for pattern-matching callback


I just want to share the use of pattern-matching callback to implement multiple modals in an app.

To implement modal, one can use this tip from dash documentation: https://dash-bootstrap-components.opensource.faculty.ai/docs/components/modal/

To implement multiple modals with a single callback, you just need to modify the “id” by adding an index:

modal = html.Div(
        dbc.Button("Open modal", {"index": 1, "role": "open"}),
                dbc.ModalBody("This is the content of the modal"),
                    dbc.Button("Close", id={"index": 1, "role": "close"}, className="ml-auto")
            id={"index": 1, "role": "modal"},

Then, a single callback with a MATCH selector will handle all modals (with different index: 1, 2…).

    Output({'index': MATCH, 'role': 'modal'}, "is_open"),
    [Input({'index': MATCH, 'role': 'open'}, "n_clicks"), Input({'index': MATCH, 'role': 'close'}, "n_clicks")],
    [State({'index': MATCH, 'role': 'modal'}, "is_open")])
def toggle_modal(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open
1 Like