Hello friends, Today we are going to discuss How to Display Icons in a Lightning Datatable in LWC(Lightning Web Component). Sometimes there is a requirement that shows Icons that user is active or not. And by the icons, we need to display the status. It will look great when we use these types of icons for any info.
Also check this: Upload Custom File in Lightning Web Component(LWC)
Highlights Points :
- Icons/image says more then words.
- Customer can easily understand.
Code :
Step1: In this step, We create a Lightning Web Component(LWC). In the HTML part just put simple Lightning Datatable. Datatable data fetch from JS part.
DatatableIconLWC.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>Display Icons in a Lightning 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-datatable
key-field="id"
columns={columns}
data={data}
hide-checkbox-column>
</lightning-datatable>
<!--- /datatable -->
</template>
DatatableIconLWC.JS:
import { LightningElement} from 'lwc';
const columns = [
{
label: 'Name', fieldName: 'Name',
},
{
label: 'Show Static Icon',
fieldName: '',
cellAttributes: { iconName: 'standard:account' }
},
{
label: 'Show Dynamic Icon',
fieldName: '',
cellAttributes: { iconName: { fieldName: 'dynamicIcon' } }
}
];
export default class DatatableIconLWC extends LightningElement {
columns = columns;
data = [
{
Id: 1, Name: 'Ankit', dynamicIcon: 'action:close'
},
{
Id: 2, Name: 'Anil', dynamicIcon: 'action:approval'
},
{
Id: 3, Name: 'Rijwan', dynamicIcon: 'action:approval'
},
{
Id: 4, Name: 'Himanshu', dynamicIcon: 'action:close'
}
]
}
Output :
Reference :
What’s your Reaction?
+1
2
+1
1
+1
1
+1
1
+1
1
+1
1
3 comments
How to sort this icon column?
We can sort the columns by column name
Thanks for posting this example. How to hover over the dynamic icons to see the alternative text? I’ve tried columnElement.typeAttributes = { alternativeText: { fieldName: “statusHover” }}; but it’s not working.