How To Add Hyper Link For Name Column In lightning-datatable in LWC

Written By Venu Gutta Salesforce LWC on Tuesday, 23 June 2020 | 05:37

Lightning Web Component (LWC) Examples: Add Hyper Link Url For Name Column/Field In lightning Data Table Example

Hello guys, in this post we are  going to see how to add hyper link url for lwc data table. As we know that if we use lightning-datatable tag we can show list of records data in table. But for name field if we use type:"text" we can't show clickable hyper link for record name on lightning Data Table. If we want display any field or column with link we need to make some tweaks on data what we are going to display on table. So that we can show link and once we click on that it will takes you to respective record page. Check below example code.

Hyper Link For Name field In lightning-datatable in LWC:

Create apex class: OpportunityController
public with sharing class OpportunityController {
    public static List<opportunity> fetchOpportunityList(){
        return [SELECT Id, Name, StageName,Amount From Opportunity LIMIT 100];

Create Lightning Web Component with name lwcDataTableHyperLink:
import { LightningElement, wire, track } from "lwc";

import getOpportunities from "@salesforce/apex/OpportunityController.fetchOpportunityList";
const COLS = [
    label: "Name",
    fieldName: "recordLink",
    type: "url",
    typeAttributes: { label: { fieldName: "Name" }, tooltip:"Name", target: "_blank" }
  { label: "Stage", fieldName: "StageName", type: "text" },
  { label: "Amount", fieldName: "Amount", type: "currency" }
export default class LwcDataTableHyperLink extends LightningElement {
  cols = COLS;
  @track oppList = [];
  getOppList({ error, data }) {
    if (data) {
      var tempOppList = [];
      for (var i = 0; i < data.length; i++) {
        let tempRecord = Object.assign({}, data[i]); //cloning object
        tempRecord.recordLink = "/" + tempRecord.Id;
      this.oppList = tempOppList;
      this.error = undefined;
    } else if (error) {
      this.error = error;
      this.oppList = undefined;

If we see above code we are not assigning wire function data directly to oppList property, instead we are modifying every record to assign link for Name column (tempRecord.recordLink = "/" + tempRecord.Id;).

    <lightning-card title="Data Table In LWC">
        <div class="slds-box">
            data={oppList} columns={cols} key-field="Id">

<aura:application extends="force:slds">


Post a comment