Py.Cafe

amward/

dash-DataTable-add-rows-clientside-callback

How to Add Rows to Dash DataTable with Clientside Callback

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 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)