Issue with dbc.Modal

Hi,

I’m beginning to experiment with dbc.Modal but I am running into some issues with callback_context. I found this sample script:

import dash
from dash import html, Input, Output, ctx,dcc
import dash_bootstrap_components as dbc
import plotly.express as px
from dash.dependencies import Input, Output
import flask
import os

server = flask.Flask('app')
server.secret_key = os.environ.get('secret_key', 'secret')
app = dash.Dash('app', server=server,external_stylesheets=[dbc.themes.SOLAR], url_base_pathname='/driver-proxy/o/0/0324-162803-s4u7bfwv/9999/')

app.layout = html.Div([
    dbc.Button("Open Modal", id="open-modal-btn", n_clicks=0),
    dbc.Modal(
        [
            dbc.ModalHeader(dbc.ModalTitle("Modal Title")),
            dbc.ModalBody("This is the content of the modal."),
            dbc.ModalFooter(
                dbc.Button("Close", id="close-modal-btn", className="ms-auto", n_clicks=0)
            ),
        ],
        id="example-modal",
        is_open=False,
    ),
])

@app.callback(
    Output("example-modal", "is_open"),
    [Input("open-modal-btn", "n_clicks"), Input("close-modal-btn", "n_clicks")],
    [dash.callback_context]
)
def toggle_modal(open_clicks, close_clicks, ctx):
    if not ctx.triggered:
        return False
    return not ctx.states["example-modal.is_open"]

if __name__ == "__main__":
    app.run(port = 8070)

But when I run it, I get the following error.


IncorrectTypeException: Callback arguments must be `Output`, `Input`, or `State` objects,

It doesn’t like the callback_context in the callback. I attempted to modify the callback by removing that line as well as the ctx in the function inputs. This allows the script to run and display the simple dashboard, but the button to display the modal doesn’t work.

Any idea how I can get this to work?

Hi @PlottingPlotly

You don’t actually need ctx for the Modal. Try changing your callback to this:


@app.callback(
    Output("example-modal", "is_open"),
    Input("open-modal-btn", "n_clicks"),
    Input("close-modal-btn", "n_clicks"),
    State("example-modal", "is_open")
)
def toggle_modal(open_clicks, close_clicks, is_open):
    if open_clicks or close_clicks:
        return not is_open
    return is_open

You can see an example like this in the DBC docs:

If you need to use ctx to see which input triggered the callback for any other reason, check out this section of the dash docs for more info and examples

1 Like