Update layout after callback, without refreshing page?

I am doing something similar here (based on another post)

Tapping the button will add more elements to the DOM. Which is great, but unfortunately, since I’m replacing them I can’t find a way to preserve their state. Any ideas?

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()
1 Like