LWC: Truncate the Text and Show View More/Less links

Ram
2 min readMar 14, 2024

Let’s imagine you have a list of cases, each with a Subject and a brief description. You want to truncate the description text and provide a “View More” link for users to expand and collapse the description as needed.

To achieve this we can utilize slds-line-clamp class to truncate the text.

Let's create one LWC component and add it to the CaseLighntingRecord Page, which shows a truncated description and a “View More” link if the text is truncated. Clicking on “View More” will expand the text, showing the full content, and the link will change to “View Less” allowing the user to collapse the text again.

customCaseDescription.html

<template>
<lightning-card title="Description" icon-name="standard:case">
<div class="slds-p-around_small">
<div class="slds-line-clamp_small content">
<lightning-formatted-rich-text value={description}></lightning-formatted-rich-text>
</div>
<div class="slds-text-align_right">
<a onclick={viewMore}>{linkName}</a>
</div>
</div>
</lightning-card>
</template>

customCaseDescription.js

import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import DESC_FIELD from "@salesforce/schema/Case.Description";

export default class CustomCaseDescription extends LightningElement {

@api recordId;

description;
linkName = 'View More'

@wire(getRecord, { recordId: "$recordId", fields:[DESC_FIELD] } )
caseRecord({ error, data }) {
if (data) {
this.description = getFieldValue(data, DESC_FIELD);
}
}

viewMore() {
if(this.linkName == 'View More') {
this.template.querySelector('.content').classList.remove('slds-line-clamp_small');
this.linkName = 'View Less';
} else {
this.template.querySelector('.content').classList.add('slds-line-clamp_small');
this.linkName = 'View More';
}
}
}

customCaseDescription.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>

Screenshots:

Collapsed Text:

Expanded Text:

Resources:

  1. https://www.lightningdesignsystem.com/utilities/line-clamp/

--

--