Dash DataTable drop-down filter

Viewed 3526

Dash DataTable component offers a free-text filter under the column header.

Dash free-text filter

How can I replace this filter with a drop-down filter that contains all unique values to select from?

Something that is available off-the-shelf in Excel:

Excel drop-down filter

or with some simple hack in DataTables JavaScript component

DataTables drop-down filter

I know I could use drop-drop down filter outside of a DataTable that interacts with DataTable via callbacks but I want the drop-down filter to be part of DataTable column header. In this sense, I don't want to use solution from: display datatable after filtering rows from dropdown list in dash

1 Answers

What's so bad with having dropdowns above the table?

import dash
import pandas as pd

from dash import dash_table as dt
from dash import dcc
from dash import html
from dash.dependencies import Input
from dash.dependencies import Output

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

app = dash.Dash(__name__)

states = df.State.unique().tolist()

app.layout = html.Div(
    children=[
        dcc.Dropdown(
            id="filter_dropdown",
            options=[{"label": st, "value": st} for st in states],
            placeholder="-Select a State-",
            multi=True,
            value=df.State.values,
        ),
        dt.DataTable(
            id="table-container",
            columns=[{"name": i, "id": i} for i in df.columns],
            data=df.to_dict("records")
        )
    ]
)


@app.callback(
    Output("table-container", "data"), 
    Input("filter_dropdown", "value")
)
def display_table(state):
    dff = df[df.State.isin(state)]
    return dff.to_dict("records")


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

app first display

→ Select red āŒ to Clear all

cleared table

selected options from dropdown

If you don't want the selected options to always be present/shown

One option would be to add the following CSS to a local ./assets/custom.css file:

.Select--multi .Select-value {
    display: none;
}

which would result in the following behavior:

options not shown

(you could add some title above the dropdown, or something, to indicate to "select a state", etc.)

options are still in fact chosen

Note: In this implementation case, you may likely want to additionally add the parameter row_deletable=True to the dt.DataTable. However, I just tested this, and it does not automatically repopulate the dropdown with options, so, further code would need to be invented to address that, which I imagine is possible. But you get the idea.

Related