2

I am using Dash to build an application and part of the application is displaying a data table. I convert the table from a pandas dataframe to a Bootstrap Table in Dash using the Table() function from dash-bootstrap-components.

With my table set up

import dash-bootstrap-components as dbc
import dash_html_components as html
import dash

data_table = dbc.Table(# code to construct table)

I'd like to use the dbc.Tooltip to add a tooltip to items (html.td() elements) in my data_table. My first thought was to assign each element in the table an id corresponding to its position and then attach a tooltip

tooltip = dbc.Tooltip("Tooltip text", target = id)

Then we put it all together.

app = dash.Dash(_name_)
app.layout = html.Div(
                 children = [data_table, tooltip]
             )

However, this doesn't seem to be working and I am struggling with how to implement this theoretically and cannot find much help.

UPDATE:

Here is some example code of what I am trying to do. It gives an error, if you remove the sectioned commented "REMOVE TO WORK" the code will function.

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd


app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

data = {
            "Name" : ["Tom", "Jack", "Jill", "Jane"],
            "Age"  : [21, 30, 45, 80]
        }
fixt_df = pd.DataFrame.from_dict(data)

#Setup table
table = dbc.Table(
            # Header
            [html.Thead([html.Tr([html.Th(col) for col in fixt_df.columns])])] +

            # Body
            [html.Tbody([html.Tr([html.Td(html.A(fixt_df.iloc[i][col], id = ""+str(i)+"_" + col))
                for col in fixt_df.columns])
                for i in range(len(fixt_df))])]
            ,
            hover = True,
            className = "table-responsive table-hover"
        )

items = [table]
# REMOVE TO WORK
for col in fixt_df.columns:
    for i in range(len(fixt_df)):
        items.extend([dbc.Tooltip("test", target = str(i)+"_"+col)])
# REMOVE TO WORK
app.layout = html.Div(
                children = [
                    #header
                    html.Div(
                        html.H1("Example")
                    ),
                    #table
                    html.Div(
                        items
                    )
                ]
            )

if __name__ == '__main__':
    app.run_server(debug=True)
student_t
  • 243
  • 2
  • 9

1 Answers1

2

I found your problem - for some reason the dbc.Tooltip element doesn't play well with elements that have IDs starting with a number.

To overcome this, in the element IDs and tooltip targets simply change:

str(i)+"_"+col

to:

col+"_"+str(i)

Alternatively, you can add a letter prefix:

"p_"+str(i)+"_"+col
Shovalt
  • 6,407
  • 2
  • 36
  • 51