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

Multiple-Callback Panel to Greet Someone

I made a simple example to describe my problem statement.

The output should look something like below.

Hi, Mike

Button: [Update User]

RadioItems:
(o) Mike
(_) Matt

Input: 
[insert name if not above]

Button: [Add Person to Checkpoints]

Basically, the name should be placed at the top, which is selected from the RadioItems. If the name is not in the set of RadioItems, a text box is below, which will add append another RadioItem.

I tried to code this (code below). I created two callbacks:

  1. Update the name at top when selected in RadioItems

  2. Print the current user when selected from RadioItems (and Button “Update User” selected)

    a. It would also be cool if this could flash red if the option is already available in the RadioItems using the Input Validation property of dcc.Input (I’m not sure where I’d start with this)

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

names = ['Mile', 'Matt']

app.layout = html.Div([
    html.Div(className = 'row',
    children = [
        html.P(id='write-update-person'),
        html.Button('Update User', id='submit-person'),
        dcc.RadioItems(
            id='radio',
            options=[{'label': i, 'value': i} for i in names],
            value='Michael',
            #clearable=False
        ),
        dcc.Input(id='input', value='Add name if needed...'),
        html.Button('Add Option', id='submit')])])

@app.callback(
    Output('radio', 'options'),
    [Input('submit', 'n_clicks')],
    [State('input', 'value'),
    State('radio', 'options')],
)
def callback(n_clicks,new_value,current_options):
    if not n_clicks:
        return current_options

    if value not in names:
        current_options.append({'label': new_value, 'value': new_value})

    return current_options

@app.callback(
    Output('write-update-person', 'n_clicks'),
    [Input("input", "value")]
)
def output_text(value):
    return "Hi, {}!".format(value)


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