Hi,
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: Modal - dbc docs
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.Modal(
[
dbc.ModalHeader("Header"),
dbc.ModalBody("This is the content of the modal"),
dbc.ModalFooter(
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…).
@app.callback(
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