✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Optional outputs in dash callbacks

Hi in my current dash app I have a side bar with inputs and 2 buttons which controls the main output content. I have a default page defined which is displayed during app start up. Once user clicks any button on sidebar, I change default screen to output screen by toggling ‘display’ property of style.

My current problem is I have to pass both default_page’s style and output_page’s style to my button callback. So each time my user selects an input, my button callback is triggered and entire page refreshes to show default_page until button is pressed. This makes the user experience terrible. Is there any way to have optional outputs in callbacks.

Attached sample code below.

@app.callback(
[Output(‘default_page’, ‘style’),
Output(‘results_page’, ‘children’)],
[Input(‘find’, ‘n_clicks’),
Input(‘reset’, ‘n_clicks’),
Input(‘input_1’, ‘value’),
Input(‘input_2’, ‘value’),
Input(‘input_3’, ‘value’)])
def return_page(find_click, reset_click, n1, n2, n3):
try:
ctx = dash.callback_context
if not ctx.triggered:
button_id = ‘No clicks yet’
else:
# assign button name to button_id to find which button triggered this event
button_id = ctx.triggered[0][‘prop_id’].split(’.’)[0]

        if button_id == 'find':
            if find_click:
                return {'display':'none'}, html.Div(["Output!!!"])
        elif button_id == 'reset':
            if reset_click:
                return {'display':'none'}, html.Div(["Reset!!!"])
    
    except:
        return {'display':'block'}, html.Div(["default!!!"])
    else:
        return {'display':'block'}, html.Div(["default!!!"])

If no button is clicked, the else part is executed. This is where an optional output would help me where I return only one output.

   else:
        return {'display':'block'}

thanks in advance!

any inputs here would be very helpful!

Hi @srk_76

in your else, try:

else:
       return {'display':'block'}, dash.no_update

see more info here: https://dash.plotly.com/advanced-callbacks

thank you this helped!

1 Like