How to add separate Html elements on a button click on Python Dash?

A very trivial scenario I am trying to achieve using Python dash. Adding similar elements on each button click one after another.

Below is the code.

app.layout = {
  html.Button(id='add-element-button', n_clicks=0, children='Add Input Element'),
  html.Div(id="layout")
}

@app.callback(Output('layout', 'children'),
              [Input('add-element-button', 'n_clicks')])
def add_strategy_divison(val):
    if val:
        return html.Div(id=f"heading_element_{val}",
            [
                html.H1(id=f"heading_{val}", children=f"{val} Heading"),
            ]
            )
    else:
        raise PreventUpdate

What seems to be happening is instead of adding new elements, it just overwrites the first heading element (which is successfully created on first click) with the new one along with the new id.

Does anyone have any idea what could be happening? Thanks!

Does anyone have any idea what could be happening? Thanks!

I take it you also posted this question in Stackoverflow: How to add separate Html elements on a button click on Python Dash - Stack Overflow

I posted the answer there.

1 Like