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

Resetting the active button in a dbc.Buttongroup

I am using dash_bootstrap_components and my controls are 2 dcc.Dropdowns, a dcc.DatePickerSingle, and one dbc.ButtonGroup with 12 dbc.Buttons. With help from chriddyp, I learned how to use dash.callback_context to determine what was the latest button pressed and store it in a hidden div so it is retained between callbacks. Everything works great however none of the 12 buttons appear as active.

Does anyone know the trick to be able to reset Active=True on the active button so this actually works like a ButtonGroup and doesn’t just look like one? Any redefinition of layout, which I presume is an unsupported practice anyway, clears the other elements. I have suggested repeatedly that Dash needs a ButtonGroup control that looks like X buttons but operates 100% like dcc.RadioItems (one always active). I know I can also use tabs or radioitems, but really want buttons.

You can use a callback with multiple outputs to target the active props of each of your buttons, and use the hidden div as an input. It might look something like this

@app.callback(
    [Output(f"button-{i}", "active") for i in range(12)],
    [Input("hidden-div", "children")],
)
def set_active_button(button_id):
    return [button_id == f"button-{i}" for i in range(12)]

Alternatively, it’s actually possible to restyle dbc.RadioItems to look like a button group. You can find a version of that here, it doesn’t use Bootstrap button styles, but the basic idea should be relatively easy to adapt.

thank you so much Tom. Copied your code and with a few simple edits, it worked the very first time! The list comprehension block is nice too as I had all 12 buttons listed in my callback that sets the hidden-div value. Now I clearly understand how to modify the form elements outside the layout definition and will use this technique again and again.

1 Like