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

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: https://stackoverflow.com/questions/61210607/how-to-add-separate-html-elements-on-a-button-click-on-python-dash

I posted the answer there.

1 Like