Quantcast
Channel: 🎛️ Dash - Plotly Community Forum
Viewing all articles
Browse latest Browse all 6271

Reusable Dash components with callback functions

$
0
0

Hi everybody,

I just discovered that with this coding pattern, I can generate UI elements with their own callbacks, that can be reused in different contexts.

Based on the Dash intro example, I found that instead of coding the layout directly


app.layout = html.Div([
    html.H6("Change the value in the text box to see callbacks in action!"),
    html.Div(["Input: ",
              dcc.Input(id='my-input', value='initial value', type='text')]),
    html.Br(),
    html.Div(id='my-output'),

])

one can create a function that generates the layout and its callbacks:

def InputField(id):

    @app.callback(
        Output(component_id='my-output' + id, component_property='children'),
        Input(component_id='my-input' + id, component_property='value')
    )
    def update_output_div(input_value):
        return 'Output: {}'.format(input_value)

    return html.Div(["Input: ",
            dcc.Input(id='my-input' + id, value='new', type='text'),
            html.Br(),
            html.Div(id='my-output' + id)
            ])

and then use the function within the main layout:

app.layout = html.Div([
    html.H6("Change the value in the text box to see callbacks in action!"),
    im.InputField('feld1'),
    im.InputField('feld2'),
    im.InputField('feld3'),
])

So far, it is working fine for me. I can not extend the layout during runtime dynamically though, but apart from that this is working quite well.

Since I did not find this pattern proposed in the main guides (only here for the layout Part 2. Layout | Dash for Python Documentation | Plotly) I was wondering, whether there are any reasons not to use this pattern?

Best,
Martin

3 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 6271

Trending Articles