Highlighting selected rows

I’m looking to highlight only selected rows in the dash table, but I can only get it to highlight the entire table. The app.callback I am using is modified from code to highlight selected columns (found here):

    @app.callback(Output('datatable-interactivity', 'style_data_conditional'),
                 [Input('datatable-interactivity', 'selected_rows')])
    def update_styles(selected_rows):
        return [{'if': {'derived_virtual_selected_row_ids': i}, 'background_color': '#D2F3FF'} for i in selected_rows]

https://dash.plotly.com/datatable/conditional-formatting

Hi @Eduardo, which part of that page specifically are you referring to? I can’t see anything about highlighting selected rows.

You are right, there is no part of the page saying that.

But the specific part of the code that say:


'if': {
                'row_index': 5

Perhaps could be part of the solution you are searching for. :neutral_face:

Hi @elliohow

Here is a sample app that shows how to highlight selected rows. One of the keys is to make sure there is a row id

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

app = dash.Dash(__name__)

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

app.layout = html.Div(
    dash_table.DataTable(
        id="table",
        row_selectable="multi",
        columns=[{"name": i, "id": i} for i in df.columns if i != "id"],
        data=df.to_dict("records"),
        page_size=4,
        filter_action="native",
    )
)


@app.callback(
    Output("table", "style_data_conditional"),
    Input("table", "derived_viewport_selected_row_ids"),
)
def style_selected_rows(selRows):
    if selRows is None:
        return dash.no_update
    return [
        {"if": {"filter_query": "{{id}} ={}".format(i)}, "backgroundColor": "yellow",}
        for i in selRows
    ]


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

4 Likes

This solves it, I was missing both filter_query and an “id” column. Thanks!