How to add button to LWC lightning-datatable?

In Salesforce, you get a LWC base component to display data in a tabular format. This based component provides various typeAttribute which can be used to configure the column fields in a user friendly way. In same you also get an option to provide row actions for each record/row in the data table. This is shown as a single dropdown on each row in one column. Following is a sample column definition of Edit and View Account actions which can be used in accounts data table.

Now to implement the code for these action you have to use, onrowaction JS handler on the lightning-datatable base component. In the handlers event details you get the row information using event.detail.row property.

A detailed example of same is available in the LWC base component library HERE.

There could be a scenario that you want to show row button instead of row actions (dropdown) on each row. In such cases, you can also make use of button type of column as shown below:

Only difference here is that we cannot club multiple buttons in a single column. If you see above column definition carefully, you will observe that there is only one button action ‘Edit Account‘ in this column definition compared to the previous example which had two actions in the action type of column.

Apart from this, the onrowaction handler will be implemented the same way. In the handler, event.detail.action.name is used to understand which action was triggered OR which button was clicked.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *