Highlighting selected rows in a Datatable with pagination

Hello, I am trying to highlight selected rows with pagination. The idea is if a row or a cell within that row is selected, the row would highlight. I have managed to get this working for the first page of the datatable but it does not work for any of the other pages. Also, currently when I select a row on the first page and go to a different page, the row remains highlighted. Can someone help me. Below is my code:

dbc.Row(
        [
        dbc.Col([ dash_table.DataTable(
             id='table',
             columns=[{"name": i, "id": i} for i in df.columns],
             data=df.to_dict('records'),
             editable=False,
             row_selectable='single',
             cell_selectable=True,
             page_size=10,
             fixed_rows= {'headers':True},
             filter_action="native",
             filter_options={"placeholder_text": "Search..."},
             #fixed_columns={'headers': True, 'data': 2},
             style_data={'color': 'black','backgroundColor': '#CDE5E8','minWidth': '125px'},
             style_data_conditional=[{'if': {'row_index': 'odd'},'backgroundColor': 'rgb(232, 242, 244)'}],
             style_header={'backgroundColor': 'rgb(46, 179, 190)','color': 'white','fontWeight': 'bold','textAlign': 'left'},
             style_table={'overflowX': 'auto','overflowY': 'auto','height':'360px','minWidth': '100%'},
             #style_cell={'whiteSpace': 'pre-wrap'}
         ),html.Div(id='hidden-div', style={'display':'none'})],
            width={'size': 12, 'offset': 0}
        )
        ], justify='center', class_name='pb-3 pt-1',style={'backgroundColor':'rgb(232, 242, 244)'}
    )
#Highlights Selected Row in Table
@callback(
    Output('table', 'style_data_conditional'),
    Input('table', 'selected_rows'),
    Input('table', 'page_cuurent')
)
def update_styles(selected_rows,page_current):
    print('page_current= '+str(page_current))
    if selected_rows is not None:
        # Create a list of style dictionaries for the selected rows
        selected_style = [{'if': {'row_index': i}, 'background-color': '#3D9970'} for i in selected_rows]
        print('selected_rows= '+str(selected_rows))
        print('selected_style= '+str(selected_style))
    else:
        selected_style = []
    
    # Add the striped style to the selected style
    striped_style = [{'if': {'row_index': 'odd'},'backgroundColor': 'rgb(232, 242, 244)'}]
    return striped_style+selected_style

HI @Kmike

This is much easier using Dash AG Grid. The rows are highlighted by default - no callback required.

To change the default highlight, you can use css, like in this example:

2 Likes

Thanks for the suggestion @AnnMarieW

I may in the future change over, but for now I’d like to stick with the Dash Data Table. I work on a network that is not connected to the internet and the Dash that is installed is an older version that does not have Dash AG Grid.

You could try this example: