Callback interaction between 2 core components

Hi ,

I am new to dash and i am trying to create a dashboard with 2 dropdown cc. The first one chooses a category and the second one based on the first one chooses subcategories.I need help on how to callback the first dropdown to affect my subcategories in the second dropdown.

Here is some sample code to get you started. Basically, you want a callback that is triggered on value of dropdown1 to returns the options and value for dropdown2. You can then have another callback handle what happens when the value for dropdown2 is changed.

import dash
import dash_html_components as html
import dash_core_components as dcc

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': 'Montréal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value='MTL'
    )

    dcc.Dropdown(
        id='dropdown2'
    )
])


@app.callback(
    output=[Output('dropdown2', 'options'),
            Output('dropdown2', 'value')],
    inputs=[Input('dropdown1', 'value')])
def update_dropdown2(value):
    if value == 'NYC':
        options=[
            {'label': 'Option 1', 'value': 'Option A'},
            {'label': 'Option 2', 'value': 'Option B'},
            {'label': 'Option 3', 'value': 'Option C'}
        ],
        value='Option B'
    elif value == 'MTL':
        options=[
            {'label': 'Option 11', 'value': 'Option AA'},
            {'label': 'Option 22', 'value': 'Option BB'},
            {'label': 'Option 33', 'value': 'Option CC'}
        ],
        value='Option CC'
    elif value == 'SF':
        options=[
            {'label': 'Option 4', 'value': 'Option A3'},
            {'label': 'Option 5', 'value': 'Option B3'},
            {'label': 'Option 6', 'value': 'Option C3'}
        ],
        value='Option A3'
    else:
        options = value = None

    return options, value
3 Likes

Hi,

Thanks for your help. Do i need to provide the options in the dcc components for the second drop down? It doesnt seem to provide any values in the second dropdown dcc?

Yes… in the update_dropdown2 function, populate the options variable as desired…what I provided was just pseudo-code to get you started, but I will edit my past post for completeness.