Dash button triggering without it being clicked

I am using the following code (which I have used in the past) for logic when a button is clicked and certain actions are to happen after:

ctx = dash.callback_context
if ‘exc_ln_button.n_clicks’ in str(ctx.triggered):
#logic when button is clicked

The logic in the if statement for when it is clicked is being triggered and throwing errors (errors are for other reasons) but it shouldn’t be triggered. Please let me know if there is a new way to show when buttons have been clicked or if I am using the wrong syntax.

Thanks in advance!

Hi @hrose33 I usually do this:

import dash
from dash import html, Input, Output, ctx, ALL
from dash.exceptions import PreventUpdate

app = dash.Dash(__name__)
app.layout = html.Div([
    html.Button('click', id='btn_0'),
    html.Button('click', id='btn_1'),
    html.Button('click', id={'type': 'btn', 'index': 0}),
    html.Button('click', id={'type': 'btn', 'index': 1}),
    html.Div(id='out')
])


@app.callback(
    Output('out', 'children'),
    Input({'type': 'btn', 'index': ALL}, 'n_clicks'),
    prevent_initial_call=True
)
def do_pattern_matching(_):
    if ctx.triggered_id.index == 0:
        raise PreventUpdate
    return ctx.triggered_id.index


@app.callback(
    Output('out', 'children', allow_duplicate=True),
    Input('btn_0', 'n_clicks'),
    Input('btn_1', 'n_clicks'),
    prevent_initial_call=True
)
def do(*_):
    if ctx.triggered_id == 'btn_0':
        raise PreventUpdate
    return ctx.triggered_id


if __name__ == '__main__':
    app.run(debug=True)

If creating content dynamically I usually do something like this:

import dash
from dash import html, Input, Output, ctx, ALL
from dash.exceptions import PreventUpdate

app = dash.Dash(__name__)
app.layout = html.Div([
    html.Button('create buttons', id='btn_0'),
    html.Div(id='button_container'),
    html.Div(id='out')
])


@app.callback(
    Output('out', 'children'),
    Input({'type': 'btn', 'index': ALL}, 'n_clicks'),
    prevent_initial_call=True
)
def do_pattern_matching(clicks):
    if not any(clicks):
        raise PreventUpdate

    if ctx.triggered_id.index == 0:
        return 'HELLO!'
    return 'HOLA!'


@app.callback(
    Output('button_container', 'children'),
    Input('btn_0', 'n_clicks'),
    prevent_initial_call=True
)
def do(_):
    return html.Div([
        html.Button('click', id={'type': 'btn', 'index': 0}),
        html.Button('click', id={'type': 'btn', 'index': 1}),
    ])


if __name__ == '__main__':
    app.run(debug=True)

mred pmcb