Hello friends, In this post we will see how to link record id in lightning datatable. Suppose you want to open a record when user click on the grid in lightning datatable, this example help you to achieve this task. So let's get started,

Link Record id in lightning datatable

Here, I am providing a code of demo lightning component, in which account name column is a clickable link that helps us to navigate on record detail page.

DatatableHandler.apxc

 public class DatatableHandler {    
@AuraEnabled
public static List<Account> getAccounts(){
return [SELECT Id,Name,Industry,AccountNumber,CreatedDate FROM Account limit 5];
}
}
LinkInDatatable.cmp
 <aura:component controller="DatatableHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global" >
<aura:attribute name="results" type="Account[]"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<lightning:layout multipleRows="true" horizontalAlign="center">
<lightning:layoutItem padding="around-small" size="12">
<lightning:datatable keyField="id" data="{!v.results}"
columns="{!v.mycolumns}"
resizeColumnDisabled="true"
hideCheckboxColumn="true"
/>
</lightning:layoutItem>
</lightning:layout>
</aura:component>
LinkInDatatableController.js
 ({
doInit : function(component, event, helper) {
component.set('v.mycolumns', [
{label: 'Account Name', fieldName: 'linkName',type: 'url',
typeAttributes:{label: { fieldName: 'Name' }, target: '_blank'}},
{label: 'Industry', fieldName: 'Industry',type: 'text'},
{label: 'AccountNumber', fieldName: 'AccountNumber',type: 'text'},
{label: 'Created Date', fieldName: 'CreatedDate',type: 'date',sortable:true,
typeAttributes:{day:'numeric',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:true}}
]);
var action=component.get("c.getAccounts");
action.setCallback(this,function(e){
if(e.getState()=='SUCCESS'){
var results=e.getReturnValue();
console.log(results);
if(results.length>0){
results.forEach(function(record){
record.linkName = '/'+record.Id;
});
component.set('v.results', results);
}
}
});
$A.enqueueAction(action);
},
})

Output:


Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.