Black Lives Matter. Please consider donating to Black Girls Code today.

Populating URL query strings based on dropdown value and dropdown value based on query string

I have a dropdown in my page. I’m trying to implement a way by which I could use query strings to pick values from the drop down(which’ll then display different plots based on the selected value). And if the user selects an item from the dropdown, it should update the URL accordingly, so that this URL along with the query string can be sent to folks who could directly view the appropriate plots instead of selecting it from the dropdown.

I tried to do something like this but I get Error loading dependencies.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

from urllib.parse import parse_qs

app = dash.Dash()

versions = ['1.0', '1.5', '2.0']

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div([

        html.Div([
            html.Label('Version'),
            dcc.Dropdown(
                id='ver-dropdown',
                options=[{'label': ver, 'value': ver} for ver in versions],
                value=versions[0]
            )

        ], style={'width': '25%', 'display': 'inline-block', 'padding': 10}),

], style={'padding': 10})
])


@app.callback(Output('url', 'search'),
              [Input('ver-dropdown', 'value')])
def change_url(version):
    query_string = '/?version={}'.format(version)
    return query_string

@app.callback(Output('ver-dropdown', 'value'),
             [Input('url', 'search'),
              Input('ver-dropdown', 'options')])
def update_version_dropdown(query, dummy):
    if len(query) <= 0:
        return versions[0]
    query = query.lstrip('?')
    query_parsed = parse_qs(query)
    return query_parsed['version'][0]


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

Is there a proper way to take query strings and display contents and also have query strings based on selected drop downs?

I discovered what the issue was. There is a cyclic dependency here.
I had to use State instead of Input for url search. I.e State('url', 'search'), and this problem went away.

@bharat I would like to do exactly this “if the user selects an item from the dropdown, it should update the URL accordingly, so that this URL along with the query string can be sent to folks who could directly view the appropriate plots instead of selecting it from the dropdown”
Can you please post a fully working example? I cannot figure out how to do this from your own answer.
thank you

Here’s an example: https://github.com/oegedijk/dash_querystrings