from typing import Dict, Optional, cast
import pandas as pd
import solara
from ipyaggrid import Grid
@solara.component
def AgGrid(df: pd.DataFrame, **kwargs):
grid_options = {
"columnDefs": [
{
"headerName": col,
"field": col,
"sortable": True,
"filter": True,
"resizable": True,
}
for col in df.columns
],
"enableSorting": True,
"enableFilter": True,
"editable": True,
"resizable": True,
"sortable": True,
}
def update_data():
widget = solara.get_widget(el)
widget.grid_options = grid_options
widget.update_grid_data(df.to_dict("records"))
el = Grid.element(
grid_data=df.to_dict("records"),
grid_options=grid_options,
quick_filter=True,
theme="ag-theme-balham",
columns_fit="auto",
index=False,
keep_multiindex=False,
**kwargs,
)
solara.use_effect(update_data, [df, grid_options])
@solara.component
def db_table():
df1 = pd.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]})
df2 = pd.DataFrame({"col3": [4, 5, 6], "col4": ["d", "e", "f"]})
df3 = pd.DataFrame({"col5": [7, 8, 9], "col6": ["g", "h", "i"]})
df_list = [df1, df2, df3]
df_names = ["df1", "df2", "df3"]
table_df = solara.reactive(cast(Optional[pd.DataFrame], None))
selected_table = solara.use_reactive("")
index = solara.reactive(None)
def find_index(my_list: list, item):
table_df.value = None
try:
position = my_list.index(item)
index.value = position
except ValueError:
position = -1
index.value = position
with solara.Column() as main:
with solara.Card(title="Select Data"):
if df_list is not None:
solara.Select(
label="Choose Data",
values=df_names,
value=selected_table,
on_value=find_index(df_names, selected_table.value),
)
solara.Markdown(f"### Seleted df : {selected_table.value}")
solara.Markdown(f"### Seleted index : {index.value}")
if index.value != -1:
with solara.Card(title=f"{df_names[index.value]} Data"):
table_df.value = df_list[index.value]
if table_df.value is not None:
solara.Markdown(f"### Solara DataTable ")
solara.DataTable(table_df.value)
solara.Markdown(f"### AgGrid DataTable ")
AgGrid(table_df.value)
return main
@solara.component
def Page():
db_table()