Search code examples
reactjsmaterial-table

push data to material-table on button click


I have material-table in my react component. I want to add row to the table dynamically when I click on button. I am not sure how to push data into table on button click with material-table

const{data, columns} = this.state;

const addMore = () => {
    data.push({ code: 'Mehmet', barCode: 'Baran', id: '1987', type: '63', createdBy: 'test' });
    console.log("push complete");
}

........

<Grid item xs={12} md={6}>
   <Button
       className={classes.button}
       color="secondary"
       variant="contained"
       onClick={addMore}
    >Add Morer</Button>
</Grid>

<Grid item xs={12}>
                <MaterialTable
                    icons={tableIcons}
                    title="Offers"
                    columns = {columns}
                    data={data}
                    actions={[
                        {
                          icon: 'delete',
                          tooltip: 'Remove',
                          onClick: (event, rowData) => confirm("You want to delete " + rowData.name)
                        }
                    ]}
                />
            </Grid>

Solution

  • Since your data is being managed by your state, in order to cause a re-render of your table with the new data you should set this data back in your state:

    const addMore = () => {
        const newRow = { code: 'Mehmet', barCode: 'Baran', id: '1987', type: '63', createdBy: 'test' }
        this.setState({data: data.concat( newRow )})
    }