From Basics to Brilliance: Elevate Your Datatable with Action Columns in LWC

Looking to enhance the user experience of your Salesforce applications? This comprehensive tutorial will guide you through the process of elevating their Datatables with action columns in LWC. By implementing action columns, you can transform your Salesforce UI from basic to brilliant, providing users with the ability to directly perform specific actions within the Datatable.

Customizing Datatable with Action Columns in LWC

You will need to incorporate the following HTML code, to begin customizing your Datatable with action columns in LWC.

Let’s dive into the customization process using HTML, JavaScript, and Salesforce-specific code.

HTML Code

<template>
     <lightning-datatable
            key-field="id"
            data={contactList}
            columns={columns}
            onrowaction={handleRowAction}
    >
    </lightning-datatable>
</template>

Explanation

In the above code snippet we have used a <lightning-datatable> component from the lightning framework. In the lightning-datatable we have assigned values to data, columns and onrowactions attributes.

data : In the data attribute we pass the list of records that we want to render as a table in the UI.

columns : We pass an arrow of JSON Objects in the column attribute. The Object holds names of columns, it’s types and map it to the fields in data attribute. The JSON Objects contains a row for the action button.

//Action Column snippet from JS file of LWC
{
   type: 'button',
   typeAttributes: { iconName: 'utility:edit', label: 'Action', name: 'action' },
}

onrowaction: We pass the JS handler in onrowaction. The handler is called when users click the action button in the datatable.

Note: If this is the first time you are using <lightning-datatable> make sure to go through the previous article on Using Lightning Datatable in LWC with Apex.

JS Code

import { LightningElement,wire,api } from 'lwc';
import getContactRecords from '@salesforce/apex/ContactController.getContactRecords';

export default class RelatedAccountContacts extends LightningElement {


     //JSON array with a row for setting up action column in datatable
     columns = [
        { label: 'Email', fieldName: 'Email', type: 'email' },
        { label: 'Name', fieldName: 'Name', type: 'text' },
        {
            type: 'button',
            typeAttributes: { iconName: 'utility:edit', label: 'Action', name: 'action' },
        }
    ];
    
    @api recordId; 
    contactList;

    @wire(getContactRecords,{accountId:'$recordId'})
    contactListRec({data,error}){
        
        if(data){
            console.log('data : ',data);
            let contactRecArr = [];
            data.forEach((eachRec)=>{
                contactRecArr.push({
                    Email:eachRec.Email,
                    Name:eachRec.Name,
                    dynamicIcon:'utility:down'
                });
            })
            this.contactList = contactRecArr;
        }else if(error){
            console.log('error',error);
        }
    }

   //Method called when the action button is clicked in the Datatable
    handleRowAction(event){
        const actionName = event.detail.action.name;
        const row = event.detail.row;

        if (actionName === 'action') {
            // You can perform any action here, for now, showing an alert
            alert(`Action Clicked`);
        }
    }
}

Explanation

This JavaScript code is responsible for displaying the action column and managing the onclick event handling.

First

We need to show a column in LWC Datatable with an action button. The columns variable is where we configure and tell the Datatable which columns to show and map it to the right data returned from @wire call.

As you can see in the snippet below, we first mention a type as button and the setting up the type attribute.

{
     type: 'button',
     typeAttributes: { iconName: 'utility:edit', label: 'Action', name: 'action' },

type = The column type is defined with the type attribute. For example: A column type can be percent, currency, date, email, etc.

typeAttribute = This typeAttribute lets us set up how things look and work for the type we talked about. We pick an icon to display, name the button, and give it a special name so we know which action is taken when a row is clicked.

To learn more about using icons in LWC, you can read our previous article on How to Use SLDS Icons in LWC with lightning-icon

Second

After successfully showing an action column in the lightning-datatable, now is the time to handle on click events. Remember we set a onrowaction attribute to handleRowAction js method handler earlier in our HTML Code.

The handleRowAction method is called when the user click on the action button. With the event parameter passed in the method, we can extract the action name which is clicked and take relevant actions.

const actionName = event.detail.action.name;

A lightning-datatable can have multiple action buttons but all of them have a single onrowaction handler. The only way to identify the action button is by giving it a unique name (while setting up columns). and then extracting the same using event.detail.action.name.

salesforce

You can read the complete Salesforce documentation on lightning-datatable here

Demo

Conclusion

After going through the above article you should now have a fair understanding of how to show and handle click event for datatable with action columns in LWC.

By customizing your datatables, you can provide a more dynamic and interactive user experience.

Feel free to utilize the provided code snippets in your personal Salesforce org and share this article with your fellow developers. Don’t forget to subscribe to our newsletter for more Salesforce development tips. If you have any issues or suggestions, please feel free to use the comment section below.