Linking Multiple RadioItems components

Rooted from Multiple Linked RadioItems
I think the answer here missed the point (or rather gave an answer specific to that example), this can be abstracted (and so is not specific to op’s particular case)
Let’s say I have 2/multiple lists that I can’t combine into one dcc.RadioItems component. I need to have multiple components.
How would we go about ‘linking them’ aka deselecting another RadioItems when one is selected?

The first thing that comes to mind is a simple callback that sets the ‘value’ of all other RadioItems to None when one RadioItems is selected. However, this would be bad to implement as you would need one callback for every RadioItems component.

What is a good way that will clear the other RadioItems?

Hi @pu239

You can link them like the “Synchronizing Two Checklists” example on this page: Advanced Callbacks | Dash for Python Documentation | Plotly

Here’s an example with multiple RadioItems:


from dash import Dash, dcc, html, Input, Output, callback_context

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

app = Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(
    [
        dcc.RadioItems(
            id="radio1",
            options=[{"label": i, "value": i} for i in ["option1", "option2","option3"]],
            value=None,
            labelStyle={"display": "inline-block"},
        ),
        dcc.RadioItems(
            id="radio2",
            options=[{"label": i, "value": i} for i in ["option4", "option5","option6"]],
            value=None,
            labelStyle={"display": "inline-block"},
        ),
    ]
)
@app.callback(
    Output("radio1", "value"),
    Output("radio2", "value"),
    Input("radio1", "value"),
    Input("radio2", "value"),
)
def sync_radio_items(radio1_val, radio2_val):
    ctx = callback_context
    input_id = ctx.triggered[0]["prop_id"].split(".")[0]
    if input_id == "radio1":
        return radio1_val, None
    else:
        return None, radio2_val


if __name__ == "__main__":
    app.run_server(debug=True)

1 Like