I am trying to build an dash app that has two tabs and each of them have the same table. I want to be able to add the rows from one tab to another tab table. For example, if I click add from recommended candidates table it should add that candidate to the candidate tab table and vice versa.
I have tried the following but I am having issue with the call back as it is not triggering it when I select a row and click “Add” from the action column.
import dash
from dash import dcc, html, Input, Output, State
import dash_bootstrap_components as dbc
import dash_table
import pandas as pd
# Sample data for demonstration
candidates_df = pd.DataFrame({
'Name': ['Candidate 1', 'Candidate 2', 'Candidate 3'],
'Age': [30, 25, 28]
})
recommended_df = pd.DataFrame({
'Name': ['Recommended 1', 'Recommended 2'],
'Age': [32, 27],
'Action': ['Add', 'Add']
})
# Initialize the Dash app
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.config.suppress_callback_exceptions = True
# Define app layout
app.layout = html.Div([
dcc.Tabs(id='tabs-example', value='tab-1', children=[
dcc.Tab(label='Candidates', value='tab-1'),
dcc.Tab(label='Recommended Candidates', value='tab-2'),
]),
html.Div(id='tabs-content')
])
# Callback to render the content of the tabs
@app.callback(
Output('tabs-content', 'children'),
Input('tabs-example', 'value')
)
def render_content(tab):
if tab == 'tab-1':
return html.Div([
html.H3('Candidates'),
generate_table(candidates_df, 'candidates-table'),
])
elif tab == 'tab-2':
return html.Div([
html.H3('Recommended Candidates'),
generate_table(recommended_df, 'recommended-table'),
])
else:
return html.Div("404 Error: Page not found")
# Callback to handle adding a candidate
@app.callback(
Output('candidates-table', 'data'),
Input('recommended-table', 'active_cell'),
State('recommended-table', 'data'),
State('candidates-table', 'data'),
prevent_initial_call=True
)
def add_candidate(active_cell, recommended_data, candidates_data):
if active_cell and active_cell['column_id'] == 'Action':
row_index = active_cell['row']
candidate_to_add = {k: recommended_data[row_index][k] for k in ['Name', 'Age']}
candidates_data.append(candidate_to_add)
print(f"Added candidate: {candidate_to_add}") # Debugging statement
return candidates_data
print("Callback triggered but no action taken")
return candidates_data
# Function to generate a Dash DataTable
def generate_table(dataframe, table_id, editable=True):
columns = [{'name': col, 'id': col} for col in dataframe.columns]
return dash_table.DataTable(
id=table_id,
columns=columns,
data=dataframe.to_dict('records'),
editable=editable
)
if __name__ == '__main__':
app.run_server(debug=True)