Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

Preserving state in dynamic dom elements in Dash

I’m trying to dynamically add elements to the DOM in Dash. Was able to figure out how with the advice of another poster, however now I’m preserve their state such that they don’t get reset every time a new element is added. I tried passing the elements in as inputs on the callback so I could re-load their state when I rebuilt them in the update method. It however did not work.

Also side note, I needed to have an extra dropdown underneath my dynamically added dropdowns in order for them to be displayed? As is shown in the div id’ed strangeness. I can just hide this, but seems weird that it’s needed.

Code posted below:

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

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.Button('Add', id='button'),
        html.Div(id='div_variable'),
        html.Div(
            [
                dcc.Dropdown(
                    id='strangeness',
                    options=[{'label': i, 'value': i} for i in range(3)],
                    value=1
                )
            ]
        )
    ]
)

@app.callback(
    Output('div_variable', 'children'),
    [Input(component_id="button", component_property="n_clicks")]
)
def update_div(num_div):

    if num_div is None:
        num_div = 0

    return [dcc.Dropdown(
                    id='div_num_dropdown' + str(i2),
                    options=[{'label':i, 'value':i} for i in range (100)],
                    value=1
                ) for i2 in range(num_div)]


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

I tried the following:

@app.callback(
    Output('div_variable', 'children'),
    [Input(component_id="button", component_property="n_clicks")] + [Input(component_id="button" + str(x), component_property="n_clicks") for x in range(app.num_dropdowns)]
)
def update_div(*args):

Though I am incrementing the app.num_dropdowns the num of variables in the args tuple always remains set to whatever app.num_dropdowns starts at.

Any ideas appreciated!