Search code examples
pythonreactjsflashdashboardplotly-dash

How to create or mount dash component after clicking on other component like button or checkbox


I created a global df variable, and I also created a csv file upload component and component that show df columns. I would like when I load the file that the component options change but I have this error options[0].label in Dropdown with ID "col-1" is required but it was not provided. How can I solve this?

Here is the sample of my code:

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

app = dash.Dash()

# I create a global variable 
global df
app.layout = html.Div(

# upload component
dcc.Upload(
        id='upload-df',
        children=html.Div([#code ]),
        }),
    html.Div(id='output-upload'),
    html.button(id='show'),
    html.Div(id='col-choice', children=[
                        html.Label('column 2'),
                        dcc.Dropdown(id='col-1'),
                        html.Label('column 2'),
                        dcc.Dropdown(id='col-2')

)

# parser
def parse_contents(contents, filename, date):
     # code
@app.callback(Output('output-upload', 'children'),
              Input('upload-data', 'contents'),
              State('upload-data', 'filename'),
              State('upload-data', 'last_modified'))
def update_output(list_of_contents, list_of_names, list_of_dates):
    # code

@app.callback(
    Output('col-1', 'options'),
    Output('col-22', 'options'),
    Input('show', 'n_clicks')
)
def show_colomn_option(clicks):
    number_of_output = 8
    try:
        df
        return ([{'label': i, 'value': i} for i in df.columns],)*2
    except NameError:
        return ([{'label': None, 'value': None}],)*2

I code upload component like discribe in this


Solution

  • Dash doesn't support global variables very well, basically it breaks your code, so you should do as described here https://dash.plotly.com/advanced-callbacks