How to use a custom LWC component in a Lightning Datatable?

How to use a custom LWC component in a Lightning Datatable?

On April 10, 2025, Posted by , In LWC Essentials, With Comments Off on How to use a custom LWC component in a Lightning Datatable?

Question:

How can we integrate a custom Lightning Web Component (LWC) into a lightning-datatable? For example, if we want to include a file upload feature for each record in the datatable, how can this be achieved?

Answer:

To achieve this, we need to create a custom LWC component that integrates with the lightning-datatable. The process involves defining a custom data type for the file upload feature and extending the lightning-datatable to use this type.

Boost your career with expert Salesforce training in Chandigarh—join our free demo and start your journey to certification today!!!

Step 1: Create the Custom Component

First, create the custom file upload component (pocCustomComp). This component will accept a recordId and allow file uploads.

pocCustomComp.html:

<template>
    <div>
        Id: {recordId}
    </div>
    <lightning-file-upload label="Upload"
                           name="fileUploader"
                           accept={acceptedFormats}
                           record-id={recordId}
                           onuploadfinished={handleUploadFinished}>
    </lightning-file-upload>
</template>

Code explanation:
The provided code defines an HTML template for a Lightning Web Component (LWC) that displays the recordId and includes a lightning-file-upload component. The file upload allows users to upload files associated with the specified recordId, accepting formats specified in acceptedFormats. The onuploadfinished event handler triggers a function to handle post-upload logic, such as dispatching events or showing a toast message.

pocCustomComp.js:

import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class PocCustomComp extends LightningElement {
    @api recordId;
    @api acceptedFormats;

    handleUploadFinished() {
        this.dispatchEvent(new CustomEvent('uploadfinished', {
            composed: true,
            bubbles: true,
            cancelable: true,
            detail: {
                data: { name: 'some data', recordId: this.recordId }
            }
        }));
        this.dispatchEvent(new ShowToastEvent({
            title: 'Completed',
            message: 'File has been uploaded',
        }));
    }
}

Code explanation:
This code defines a Lightning Web Component (LWC) named PocCustomComp, which enables file uploads for a specific record. It accepts two properties, recordId and acceptedFormats, to identify the record and restrict file types. When a file upload is completed, it dispatches two events: a custom event (uploadfinished) with the uploaded file’s details and a ShowToastEvent to display a success message to the user.

Step 2: Extend lightning-datatable to Use the Custom Component

Now, create a new component that extends the lightning-datatable and defines a custom data type for the file upload feature. We will use the template of the custom component created earlier (pocFileUpload).

pocLightningDatatable.js:

import LightningDatatable from 'lightning/datatable';
import pocFileUpload from './pocFileUpload.html';

export default class PocLightningDatatable extends LightningDatatable {
    static customTypes = {
        fileUpload: {
            template: pocFileUpload,
            typeAttributes: ['acceptedFormats'],
        }
    };
}

Code explanation:
The code extends the lightning-datatable base class to create a custom datatable component named PocLightningDatatable. It defines a custom data type fileUpload, specifying a template (pocFileUpload.html) and a set of type attributes (acceptedFormats) to pass dynamic data to the custom component. This allows the datatable to render the fileUpload type cells using the specified custom template.

pocFileUpload.html:

<template>
    <c-poc-custom-comp record-id={value}
                       accepted-formats={typeAttributes.acceptedFormats}>
    </c-poc-custom-comp>
</template>

Code explanation:
This code snippet defines a template that uses the custom Lightning Web Component poc-custom-comp. It passes the record-id attribute as the value of the corresponding field in the datatable and binds the accepted-formats attribute to typeAttributes.acceptedFormats, ensuring dynamic configuration based on the datatable’s column definition. The component facilitates specific functionality (e.g., file upload) for each row, with attributes tailored to the data and type requirements.

Step 3: Use the Extended Datatable Component

Once the custom lightning-datatable is defined, you can use it wherever needed. The columns definition should include the custom data type (fileUpload) for the file upload functionality.

poc.html:

<template>
    <c-poc-lightning-datatable key-field="id"
                data={data}
                columns={columns}
                onuploadfinished={handleUploadFinished}
                hide-checkbox-column>
    </c-poc-lightning-datatable>
</template>

Code explanation:
This code defines a template for a Lightning Web Component that uses a custom poc-lightning-datatable component. The key-field="id" ensures each row is uniquely identified, and the data and columns attributes provide the dataset and column configuration, including custom types like fileUpload. The onuploadfinished event handler listens for file upload completion events, while hide-checkbox-column hides the default selection checkboxes in the datatable.

poc.js:

import { LightningElement, track } from 'lwc';
import findAccounts from '@salesforce/apex/poc.findAccounts';

export default class Poc extends LightningElement {
    @track data = [];
    
    connectedCallback() {
        this.columns = [
            { label: 'Name', fieldName: 'Name' },
            { label: 'Account Number', fieldName: 'AccountNumber' },
            { label: 'Upload', type: 'fileUpload', fieldName: 'Id', typeAttributes: { acceptedFormats: '.jpg,.jpeg,.pdf,.png' } }
        ];
        findAccounts().then(res => { this.data = res; }).catch(err => console.error(err));
    }

    handleUploadFinished(event) {
        event.stopPropagation();
        console.log('data => ', JSON.stringify(event.detail.data));
    }
}

Step 4: Apex Class for Data Retrieval

Lastly, you can create an Apex class to retrieve data for the datatable.

poc.cls:

public without sharing class poc {
    @AuraEnabled(cacheable=true)
    public static List<Account> findAccounts() {
        return [SELECT Name, AccountNumber from Account LIMIT 10];
    }
}

Code explanation:
The given code defines a public Apex class poc marked as “without sharing,” meaning it does not enforce the sharing rules of the running user. The class contains a static method findAccounts, annotated with @AuraEnabled(cacheable=true), making it accessible to Lightning components and enabling caching for better performance. The method retrieves the first 10 Account records, specifically their Name and AccountNumber fields, from the database using a SOQL query and returns the result as a list.

Summing Up:

Integrating a custom LWC component into a lightning-datatable enables advanced functionality like row-specific actions, such as file uploads. By extending lightning-datatable and defining custom data types, you can seamlessly embed custom components that interact with the underlying data. This approach combines flexibility and reusability, providing a powerful solution for building interactive and user-friendly datatables in Salesforce.

Salesforce Training in Chandigarh – Accelerate Your Career Today!

Unlock your potential with our industry-recognized Salesforce training program in Chandigarh, tailored for aspiring professionals and seasoned experts alike. Gain in-depth knowledge of Salesforce CRM, hands-on experience with real-world projects, and expert guidance to help you ace certifications like Salesforce Admin and Developer. Our curriculum is designed to make you job-ready and elevate your career to new heights.

Our focuses on practical, industry-relevant learning. Salesforce training in Chandigarh With personalized guidance, comprehensive course materials, and expert support for certification and interview prep, we make sure you’re job-ready.

Enroll today for a free demo session and take the first step towards a successful Salesforce career!!!

Comments are closed.