One callback to fill a div and another to clear same div

Say I have one div and two buttons outside. I want to implement callback for each button. First button callback is to fill some text in the div and hence use (div,children) as output. I want the second button callback to clear the data.

Problem is that if I use same div as=gain for second callback it will complain about duplicate Output.

How to handle this kind of situation

Thanks in advance

I think the best way is to write a callback that takes both buttons as inputs, then uses dash.callback_context to figure out which one was clicked and update the contents accordingly. Check out How do I determine which Input has changed? in the docs for more details on that. Then your callback can be something along the following lines:

    Output("my-div", "children"),
    [Input("button-1", "n_clicks"), Input("button-2", "n_clicks")],
def make_contents(n1, n2):
    # use dash.callback_context to figure out which button was clicked

    if button_1_was_clicked:
        # return the text you want to put in the div
    elif button_2_was_clicked:
       # return the empty content
1 Like

Is it the only way. Because this was an example. I have couple of requirements like this. Another example is to print some message from different callbacks to a single div.

A hacky way to give multiple callbacks control over a single div is to add a wrapper, so you have something like

html.Div(html.Div(id="my-div"), id="my-div-wrapper")

Then you can give one callback control of my-div.children and another control of my-div-wrapper.children, which of course includes everything in my-div.children. This can be a bit messy though.

In your second example where you want to print different messages from different callbacks to a single div, you could have each message get saved to a hidden div or a dcc.Store component, then have a single unifying callback that takes the hidden divs / Stores as input, and chooses the appropriate output for the div you care about.