Data Tables in LWC (Lightning Web Components)

Data Tables in LWC - let me walk you through how to use lightning datatable to display data in tabular format.

Data Tables in LWC (Lightning Web Components)

Data Table in LWC is one of the popular base components that you will reach out to whenever you want to display a list of records.

Data Tables are very popular in Aura Components and in Salesforce Classic too, with the only difference that they are referred to as Page Block Tables.

The reason why it is so easy to work with and easy to configure is, we don't have to deal with a ton of options.

We only need to control the JSON string that is being passed as the input to <lightning-datatable /> tag and rest everything will be taken care of by the base component.

In case you are here for some advanced scenarios, this is for you Advanced Data Tables in LWC
Basic Data Table in LWC(Lightning Web Components)

This is how the tag is going to look like. If you notice it there is no fuss at all, it's pretty much simple.

<!-- We are looking at display data in 
   tabular format with data being fed 
   to data and columns attribute.-->
<lightning-datatable
   key-field="id"
   data={data}
   columns={columns}>
</lightning-datatable>

Template file using Datatable base component tag

This is how columns will be sourced to the tag in the template file from the web components js file.

const columns = [
        { label: 'Name', fieldName: 'Name' },
        { label: 'Rating', fieldName: 'Rating' },
        { label: 'Industry', fieldName: 'Industry' }
    ];

Configuring the columns in the JS Controller

This is how we are trying to source the data to data tables in LWC.

import {
    LightningElement,
    track
} from 'lwc';

import getAccounts from '@salesforce/apex/exploreDatatableController.getAccounts';

const columns = [{
        label: 'Name',
        fieldName: 'Name'
    },
    {
        label: 'Rating',
        fieldName: 'Rating'
    },
    {
        label: 'Industry',
        fieldName: 'Industry'
    }
];

export default class ExplorePagination extends LightningElement {

    @track data;

    //wiring the apex method to a function 
    @wire(getContacts)
    wiredContacts({
        error,
        data
    }) {
        //Check if data exists 
        if (data) {
            this.data = data;
            // eslint-disable-next-line no-console  
            console.log(JSON.stringify(data));
        } else if (error) {
            // eslint-disable-next-line no-console
            console.log(error);
        } else {
            // eslint-disable-next-line no-console
            console.log('unknown error')
        }
    }
}

Do not forget to add values to isExposed and targets tags in the web components XML file.