Custom Type in Datatable in LWC

by Rijwan Mohmmed
how-to-use-custom-type-in-lightning-datatable-in-lightning-web-component(lwc)-techdicer

Hello friends, today we are going to discuss How to use Custom Type in Lightning Datatable in Lightning Web Component(LWC). We will define a new custom type for Lightning Datatable so we can show images, custom buttons, etc.

Predefined types like:

  • date
  • boolean
  • date-local
  • email
  • location
  • number
  • percent
  • phone
  • text
  • URL
  • button
  • button-icon
  • currency
  • actions

Also, check this: Create LWC Toast Messages in Salesforce

how-to-use-custom-type-in-lightning-datatable-in-lightning-web-component(lwc)--techdicer
how-to-use-custom-type-in-lightning-datatable-in-lightning-web-component(lwc)–techdicer

Highlights Points :

  1. We can show image in Datatable columns.
  2. Show toggle button.
  3. show the data with images and texts.
  4. Can put custom components or embed the LWC components in Datatable columns.
  5. Like we can put inputs like file types in Lightning Datatable.

Code :

Step 1: In this step, we will create a button custom column component.

ButtonColumnLWC.HTML:

<template>
    <lightning-button variant="brand"
                     label={buttonName} title={buttonName} 
                     onclick={handleClick} 
                     class="slds-m-left_x-small">
    </lightning-button>
</template>

ButtonColumnLWC.JS :

import { LightningElement, api } from 'lwc';
export default class ButtonColumnLWC extends LightningElement {
    @api recordId;
    @api buttonName;

    handleClick(){
        let paramData = {recordId : this.recordId, buttonName : this.buttonName};
        console.log(paramData);
        const ev = new CustomEvent('buttonmethod', {
            composed: true,
            bubbles: true,
            cancelable: true,
            detail: paramData,
        });
        this.dispatchEvent(ev);
    }
}

Step 2: Here we create LWC components for custom type columns. We will extend LightningDatatable in the JS class. In this way, we can define new custom columns. We will create new HTML files along with this component. And in these components, we will put data or images accordingly. See below image

how-to-use-custom-type-in-lightning-datatable-in-lightning-web-componentlwc-techdicer
how-to-use-custom-type-in-lightningdatatable-in-lightning-web-componentlwc-techdicer

CustomDatatableType.HTML:

<template>

</template>

CustomDatatableType.JS:

import LightningDatatable from 'lightning/datatable';
import imageColumn from './imageColumn.html';
import buttonColumn from './buttonColumn.html';
import staticbuttonColumn from './staticbuttonColumn.html';

export default class CustomDatatableType extends LightningDatatable {
    static customTypes = {
        imageColumn: {
            template: imageColumn,
            typeAttributes: ['imgUrl']
        },
        buttonColumn: {
            template: buttonColumn,
            typeAttributes: ['recordId', 'buttonname']
        },
        staticbuttonColumn: {
            template: staticbuttonColumn,
            typeAttributes: ['recordId', 'buttonname']
        }
    };
}

imageColumn.HTML:

<template>
  <img src={imgUrl} alt={imgUrl}/>
</template

buttonColumn.HTML:

<template>
    <c-button-column-l-w-c record-id={typeAttributes.recordId} button-name={typeAttributes.buttonname}>
    </c-button-column-l-w-c>
</template>

staticbuttonColumn.HTML:

<template>
    <c-button-column-l-w-c record-id={typeAttributes.recordId} button-name={typeAttributes.buttonname}>
    </c-button-column-l-w-c>
</template>

Step 3: In the first step, we will create a Lightning Web Component to show the data in Lightning Datatable. This is the base component where we feed the data in Datatable. You can say this component is parent component.

LWCCustomDatatable.HTML:

<template>
    <!-----header-------->
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>Custom Type in Datatable in LWC</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <!-----/header-------->

    <!-- datatable -->
    <lightning-card  title="Custom Type Columns Datatable" icon-name="standard:account">
        <c-custom-datatable-type key-field="id"
                                 data={data} 
                                 columns={columns} 
                                 hide-checkbox-column
                                 onbuttonmethod={handleButtonMethod}>
        </c-custom-datatable-type>
    </lightning-card>
    <!-- /datatable -->
</template>

LWCCustomDatatable.JS:

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

const columns = [   
                    { label: 'Name', fieldName: 'name' },
                    { label: 'Type', fieldName: 'type' },
                    { label: 'Image', fieldName: 'id', type: 'imageColumn', typeAttributes: {
                            imgUrl: { fieldName: 'imageUrl'}
                        }
                    },
                    { label: 'Static Button', fieldName: 'id', type: 'staticbuttonColumn', typeAttributes: {
                         buttonname: 'Static Button', recordId:{ fieldName: 'id'}
                        }
                    },
                    { label: 'Dynamic Button', fieldName: 'id', type: 'buttonColumn', typeAttributes: {
                            buttonname: { fieldName: 'buttonname'}, recordId:{ fieldName: 'id'}
                        }
                    },
                ];
export default class LWCCustomDatatable extends LightningElement {
    columns = columns;
    @track data = [
        { id: 1, name: 'Ankit', type: 'CS', buttonname: 'CS1', imageUrl:'https://source.unsplash.com/user/c_v_r/100x100'},
        { id: 2, name: 'Rijwan', type: 'EC', buttonname: 'EC2', imageUrl:'https://i.picsum.photos/id/887/200/200.jpg?hmac=yOynpt597y5pLfJ5SsRVVKZiT5MXElbhtgUYeRzu3S4'},
        { id: 3, name: 'Himanshu', type: 'MEC', buttonname: 'MEC3', imageUrl:'https://source.unsplash.com/user/c_v_r/100x100'},
        { id: 4, name: 'Anil', type: 'CS', buttonname: 'CS4', imageUrl:'https://source.unsplash.com/user/c_v_r/100x100'},
        { id: 5, name: 'Sachin', type: 'MSC', buttonname: 'CS5', imageUrl:'https://source.unsplash.com/user/c_v_r/100x100'},
    ];
     
    handleButtonMethod(event) {
        console.log(event.detail.buttonName);
        console.log(event.detail.recordId);
        let msg = 'ButtonName : ' + event.detail.buttonName + ' Id : ' + event.detail.recordId;
        this.ShowToast('Info', msg, 'info', 'dismissable');
    }

    ShowToast(title, message, variant, mode){
        const evt = new ShowToastEvent({
            title: title,
            message:message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(evt);
    }
}

Output :

how-to-use-custom-type-in-lightning-datatable-in-lightning-web-component(lwc)--techdicer
how-to-use-custom-type-in-lightning-datatable-in-lightning-web-component(lwc)–techdicer

Reference :

  1. Lightning Datatable
What’s your Reaction?
+1
6
+1
0
+1
1
+1
0
+1
5
+1
0

You may also like

Leave a Comment