I'm using DASH library and I'm trying to use two dropdown filters with the same id so I can filter in any of both and it calls the same callback, and if I change one, the other also need to change. But I don't know how to do it.
Thanks.
Ids should be unique. Duplicate ids in the layout are disallowed (if you're using a recent version of Dash). Dash will throw an exception if you have duplicate ids in the layout.
Instead you should give both dropdowns a unique id and include both components in your callback by their ids.
If you want to change the dropdown value of one dropdown when the other dropdown value changes you could use dash.callback_context
:
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
[
dcc.Dropdown(
id="dropdown1",
options=[
{"label": "New York City", "value": "NYC"},
{"label": "Montreal", "value": "MTL"},
{"label": "San Francisco", "value": "SF"},
],
value="NYC",
),
dcc.Dropdown(
id="dropdown2",
options=[
{"label": "New York City", "value": "NYC"},
{"label": "Montreal", "value": "MTL"},
{"label": "San Francisco", "value": "SF"},
],
value="NYC",
),
html.Div(id="output"),
]
)
@app.callback(
Output("dropdown1", "value"),
Output("dropdown2", "value"),
Input("dropdown1", "value"),
Input("dropdown2", "value"),
prevent_initial_call=True
)
def update_output(dropdown1_value, dropdown2_value):
ctx = dash.callback_context
dropdown_id = ctx.triggered[0]['prop_id'].split('.')[0]
if dropdown_id == "dropdown1":
dropdown_values = dropdown1_value, dropdown1_value
elif dropdown_id == "dropdown2":
dropdown_values = dropdown2_value, dropdown2_value
return dropdown_values
if __name__ == "__main__":
app.run_server()
If the value
property of dropdown1
changes the callback is triggered and the value
property of dropdown2
changes to the value of dropdown1
and vice versa.
prevent_initial_callback
is set to True
so I don't have to check if dash.callback_context.triggered
is not None
. You might want to change this depending on your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With