Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! ✅Check out the new docs.

Create dropdown to connect with datatable in Dash

hey, I am sure it will be very quick for someone who is not a beginner in Dash like me. I need to connect drop down to dash data table so that choosing an option in drop down selects a row in the data table.
I was able to follow some examples using the Dash community forum and managed to reach up to the code below. But, it says the ‘row’ is not defined in data table and so doesn’t work. Can anyone please have a look and let me know how to work around this.

Thanks

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

df = pd.read_csv(‘https://raw.githubusercontent.com/plotly/datasets/master/solar.csv’)

app = dash.Dash(name)

app.layout = html.Div([
dcc.Dropdown(id=‘my-dropdown’,
options=[
{‘label’: ‘California’, ‘value’: ‘CA’},
{‘label’: ‘Arizona’, ‘value’: ‘AR’},
{‘label’: ‘Nevada’, ‘value’: ‘NE’},
{‘label’: ‘New Mexico’, ‘value’: ‘NM’},
{‘label’: ‘Colorado’, ‘value’: ‘CO’},
{‘label’: ‘Texas’, ‘value’: ‘TE’},
{‘label’: ‘North Carolina’, ‘value’: ‘NC’},
{‘label’: ‘New York’, ‘value’: ‘NY’},
], value =
),
dash_table.DataTable(
id=‘my-datatable’, selectable=‘True’)
])

@app.callback(Output(‘my-datatable’, ‘derived_virtual_row_ids’), [Input(‘my-dropdown’, ‘value’)])
def update_rows(selected_value):
dff = df[df[‘Number of Solar Plants’] == value]
return dff.to_dict(‘records’)

if name == ‘main’:
app.run_server(debug=True)

Here is the edited code.In this i have taken the drop values in variable with unique state. so you can minimise the options in the drop div class.I hope it may help you.

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

df = pd.read_csv(‘https://raw.githubusercontent.com/plotly/datasets/master/solar.csv’)
available_indicators = df[‘State’].unique()

app = dash.Dash(name)

app.layout = html.Div([
dcc.Dropdown(id=‘my-dropdown’,
options=[{‘label’: i, ‘value’: i} for i in available_indicators],
value=‘Texas’),
dash_table.DataTable(
id=‘my-datatable’)
])

@app.callback(Output(‘my-datatable’, ‘selected_rows’), [Input(‘my-dropdown’, ‘value’)])
def update_rows(selected_value):
dff = df[df[‘Number of Solar Plants’] == selected_value]
return dff.to_dict(‘records’)

if name == ‘main’:
app.run_server(debug=True)