# Forum question
# https://community.plotly.com/t/add-rows-to-datatable-via-clientside-callback-not-expanding-table/86307
# How to update DataTable Row Data clientside
from dash import Dash, dash_table, dcc, html, Input, Output, State, clientside_callback
app = Dash(__name__)
app.layout = html.Div([
html.H2("How to add rows in a DataTable with a clientside callback"),
html.Button('Add Row', id='editing-rows-button', n_clicks=0),
dash_table.DataTable(
id='adding-rows-table',
columns=[{
'name': 'Column {}'.format(i),
'id': 'column-{}'.format(i),
'deletable': True,
'renamable': True
} for i in range(1, 5)],
data=[
{'column-{}'.format(i): (j + (i-1)*5) for i in range(1, 5)}
for j in range(5)
],
editable=True,
row_deletable=True
),
])
clientside_callback(
"""
function(n_clicks, rows, columns) {
if (n_clicks > 0) {
let newRow = {};
columns.forEach(column => {
newRow[column.id] = '';
});
// Create a deep copy of the rows array - ensures re-render
let newRows = JSON.parse(JSON.stringify(rows));
newRows.push(newRow)
return newRows
}
return dash_clientside.no_update
}
""",
Output('adding-rows-table', 'data'),
Input('editing-rows-button', 'n_clicks'),
State('adding-rows-table', 'data'),
State('adding-rows-table', 'columns')
)
if __name__ == '__main__':
app.run(debug=True)