Extend Lightning Datatable to display images with custom column types
This implementation creates a custom Lightning Datatable component that:
Follow these steps to implement this solution:
This component configures and uses the custom datatable.
<template>
<c-custom-data-table-type-controller
key-field="id"
data={data}
columns={columns}
hide-checkbox-column
></c-custom-data-table-type-controller>
</template>
import { LightningElement, track } from 'lwc';
// Table column definitions
const columns = [
{ label: 'Name', fieldName: 'name' },
{ label: 'Model', fieldName: 'type' },
{
label: 'Image',
fieldName: 'imageUrl',
type: 'imageColumenForDataTable', // custom column type for image
typeAttributes: {
imgUrl: { fieldName: 'imageUrl' }
}
},
];
export default class customDataTable extends LightningElement {
accountData;
header = [];
columns = columns;
// Table data
@track data = [
{ id: 1, name: 'Hyundai', type: 'Creta', buttonname: 'CS1', imageUrl:'https://imgd.aeplcdn.com/370x208/n/cw/ec/106815/creta-exterior-right-front-three-quarter-5.jpeg?isig=0&q=80'},
{ id: 2, name: 'Toyota', type: 'Fortuner', buttonname: 'EC2', imageUrl:'https://imgd.aeplcdn.com/664x374/n/cw/ec/44709/fortuner-exterior-right-front-three-quarter-21.jpeg?isig=0&q=80'},
];
}
This extends LightningDatatable to support the custom image column type.
import { LightningElement } from 'lwc';
import LightningDatatable from 'lightning/datatable';
import imageColumenForDataTable from './imageColomManage.html';
export default class customDataTableTypeController extends LightningDatatable {
static customTypes = {
imageColumenForDataTable: {
template: imageColumenForDataTable,
typeAttributes: ['imgUrl']
}
};
}
This defines how the image column should be rendered.
<template>
<img src={value} alt="Table image" style="max-height: 50px;"/>
</template>
columns array to match your field structuredata property