0

I am creating a component in Dash with rows. After a user clicks on a submit button, a figure with multiple lines (each row a line) should get created.

This rows component could have been a table component, but since my component contains buttons in one of the columns, I created it manually with divs. The reason is that the Dash DataTable does not allow "HTML" components.

The Important Thing: The first two rows contain default values. Also, there is a button that can create a new empty row, allowing the user to add new information. The user may add an arbitrary number of rows, by clicking the button multiple times.

All the new or edited information has to get saved somewhere (state) so that when the user clicks on the submit button, the figure appears.

I am still unsure if this logic is possible with Dash/Plotly. Any ideas?

P.S. I have already tried with three rows, but then I have to hardcode the Inputs and Outputs in the callback. This is no plausible solution.

Here is some sample not working code. Also, some functions would be stored as separate files as they depict some components:

from dash import Dash, html, dcc, Input, Output

app = Dash(__name__, title="Dash App")


def input_container(index: int) -> dcc.Input:
    return dcc.Input(id={'type': 'my-input', 'index': index}, value='initial value')


# mutable state
state = [input_container(1)]


def inputs_container(state) -> html.Div:
    return html.Div(id='inputs-container', children=state)


def add_input_button(app, state) -> html.Button:
    @app.callback(Output('inputs-container', 'children'), Input('add-input', 'n_clicks'), prevent_initial_call=True)
    def add_input(n_clicks):
        return state.append(input_container(len(state) + 1))

    return html.Button('Add Input', id='add-input')


def submit_button(app, state) -> html.Button:
    @app.callback(Output('graph', 'figure'), Input('submit-input', 'n_clicks'))
    def submit_input(n_clicks):
        return '' # create some figure from the state values

    return html.Button('Submit Input', id='submit-input')


app.layout = html.Div([
    inputs_container(state),
    add_input_button(app, state),
    submit_button(app, state),
    dcc.Graph(id='graph'),
])

if __name__ == '__main__':
    app.run_server(debug=True)
4
  • 2
    Hi and welcome on SO. It will be great if you can have a look at How to Ask and then try to produce a minimal reproducible example.
    – rpanai
    Commented Apr 21, 2023 at 15:23
  • Can you show us any code you've written to create your Dash app in its current form, and what your dash app looks like?
    – Derek O
    Commented Apr 21, 2023 at 15:54
  • @DerekO I added some sample code
    – Georgios
    Commented Apr 21, 2023 at 17:17
  • @Georgios I added an answer to your question. Hopefully it helps.
    – umit1010
    Commented Apr 23, 2023 at 18:07

2 Answers 2

1

It seems like you got close with the id={'type': 'my-input', 'index': index} but you did not implement the callback correctly.

You can use a dictionary for the id field and then use the ALL component in the call back and the ctx.triggered_id[] dictionary to dynamically determine which button is clicked.

Here's a simplified example for the sake of clarity:

from dash import Dash, ALL, ctx, dcc, html, Input, Output

app = Dash(__name__)

inputs = [
    dcc.Input(id='output', type='text', size='100'), html.Br()
]

for i in range(10):
    new_button = html.Button(f'click {i}', id={'type':'button', 'index':i, 'someattr':f'any data {i}'})
    inputs.append(new_button)


@app.callback(
    Output('output', 'value'),
    Input({'type':'button', 'index':ALL, 'someattr': ALL}, 'n_clicks')
)
def update_output(n_clicks):
    if ctx.triggered_id is not None:
        index = ctx.triggered_id['index']
        someattr = ctx.triggered_id['someattr']
        return f'You clicked button #{index}, which had the attribute: "{someattr}".'
    else:
      return 'Click a button.'

app.layout = html.Div(inputs)

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

A few important things to keep in mind:

  • You can add as many entries to the dictionary as you'd like to pass values to the callback.
  • You will receive a list for the n_clicks parameter, not a single number. For example, if you clicked the second button, you'd receive the following list [0 1 0 0 0 0 0 0 0 0].
  • Checking for the None value ensures that your app doesn't throw callback exceptions when the callback is triggered without clicking a button.
2
  • Thanks for the answer. I am getting in the console the following error: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. Also in this case you are only using one input field and not multiple. Why and how would this work for multiple fields?
    – Georgios
    Commented Apr 24, 2023 at 8:27
  • Also, the input content gets overwritten when I click a button. The idea is to have multiple input fields that are dynamically generated and then get their values when I click on a submit button.
    – Georgios
    Commented Apr 24, 2023 at 8:34
1

I finally got it. The info I was missing were the wildcards (MATCH, ALL, & ALLSMALLER) the pattern-matching-callbacks. There is also a fantastic tutorial in youtube Introduction to Dash Plotly Dynamic Callbacks

app.layout = html.Div([
    html.Button('Add Input', id='add-input'),
    html.Div(id='inputs-container'),
    html.Button('Submit Input', id='submit-input'),
    html.Div(id='output')
])


@app.callback(Output('inputs-container', 'children'), State('inputs-container', 'children'),
              Input('add-input', 'n_clicks'), )
def add_input(children, n_clicks):
    patched_list = Patch()
    if n_clicks is None:
        patched_list.append(dcc.Input(id={'type': 'my-input', 'index': 0}, value='initial value'))
        patched_list.append(dcc.Input(id={'type': 'my-input', 'index': 1}, value='initial value'))
    else:
        patched_list.append(dcc.Input(id={'type': 'my-input', 'index': n_clicks + 1}, value='initial value'))
    return patched_list


@app.callback(Output('output', 'children'), State({'type': 'my-input', 'index': ALL}, 'value'),
              Input('submit-input', 'n_clicks'))
def submit_input(values, n_clicks):
    return f'You clicked button #{n_clicks}, which had the attribute: "{values}".'


if __name__ == '__main__':
    app.run_server(debug=True)
1
  • 1
    Glad you were able to make it work :) I think I misunderstood your question and thought you asked about multiple buttons instead of multiple inputs.
    – umit1010
    Commented Apr 24, 2023 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.