Expandable Text
alphav0.3.0Truncating text block — plain or rich children — that shows its toggle only when text overflows; configurable clamp, bidi-safe, controlled or uncontrolled.
Context
Use for any user-authored multi-line text where the surface budget is bounded — post bodies, comment bodies, event descriptions, news excerpts, product descriptions, profile bios. Pure CSS line-clamp clips silently; this component measures scrollHeight against lineHeight × maxLines after mount + on resize, so the 'show more' toggle only appears when content actually exceeds the budget. Migration origin: kasder kas-social-front-v0 PostContent.tsx; first ship in the 8-component social-posts-system arc.
Installation
pnpm dlx shadcn@latest initpnpm dlx shadcn@latest add @ilinxa/expandable-textAdd -fixtures for dummy data:
pnpm dlx shadcn@latest add @ilinxa/expandable-text-fixturesCLI can't resolve @ilinxa? The namespace is listed in the official shadcn registry directory, so current CLIs need no configuration. If yours can't resolve it (older or pinned versions, self-hosted mirrors), register it manually in components.json:
"registries": {
"@ilinxa": "https://ui.ilinxa.com/r/{name}.json"
}Preview
Long content (toggle appears)
Spent the afternoon walking through the new market by the harbor. The vendors had set up under bright canopies, and the smell of grilled fish and fresh bread filled the air. I bought a small jar of olive paste from a woman who told me her family has been making it the same way for four generations. The texture was somewhere between butter and tapenade — earthy, salty, with a faint heat at the finish. I'll pick up another jar before we leave.
Short content (no toggle — content fits)
Just shipped a small update. Quick fix for the auth flow.
Demo source
"use client"; import { useState } from "react";import { ChevronDown, ChevronUp } from "lucide-react";import { Tabs, TabsContent, TabsTrigger } from "@/components/ui/tabs";import { SwipeTabsList } from "@/components/site/swipe-tabs-list";import { ExpandableText } from "./expandable-text";import { LONG_AR, LONG_EN, LONG_TR, SHORT_AR, SHORT_EN, SHORT_TR } from "./dummy-data"; const TR_LABELS = { showMore: "Daha fazla göster", showLess: "Daha az göster",}; const AR_LABELS = { showMore: "عرض المزيد", showLess: "عرض أقل",}; function CustomToggleDemo() { const [expanded, setExpanded] = useState(false); return ( <ExpandableText content={LONG_EN} maxLines={3} expanded={expanded} onExpandedChange={setExpanded} renderToggle={({ isExpanded, setExpanded }) => ( <button type="button" onClick={() => setExpanded(!isExpanded)} aria-label={isExpanded ? "Collapse" : "Expand"} aria-expanded={isExpanded} className="mt-2 inline-flex items-center gap-1 rounded-full border border-border bg-card px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" > {isExpanded ? ( <> <ChevronUp className="h-3 w-3" aria-hidden="true" /> Less </> ) : ( <> <ChevronDown className="h-3 w-3" aria-hidden="true" /> More </> )} </button> )} /> );} /** A host's own safe mention / hashtag / link renderer — what `children` is for. */function RichBody() { return ( <ExpandableText maxLines={3}> <span> Market day with{" "} <a href="#ayse" className="font-medium text-foreground underline decoration-primary underline-offset-2"> @ayse </a>{" "} and{" "} <a href="#deniz" className="font-medium text-foreground underline decoration-primary underline-offset-2"> @deniz </a> . {LONG_EN}{" "} <a href="#harbor" className="text-muted-foreground underline underline-offset-2"> #harbor </a> </span> </ExpandableText> );} /** Text that grows while clamped (a live edit) — re-measured from the DOM change (MutationObserver). */function GrowingBody() { const [lines, setLines] = useState(1); const text = Array.from({ length: lines }, (_, i) => `Update ${i + 1}: the thread keeps going.`).join(" "); return ( <div className="space-y-2"> <button type="button" onClick={() => setLines((n) => n + 3)} className="rounded-md border border-border bg-card px-2 py-1 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" > Add text </button> <ExpandableText maxLines={2}> <span>{text}</span> </ExpandableText> </div> );} /** * A style change (letter spacing) alters no DOM inside the text. While the box stays at its clamped * height no observer fires — `measureKey` re-measures it. */function MeasureKeyBody() { const [wide, setWide] = useState(false); return ( <div className="space-y-2"> <button type="button" onClick={() => setWide((w) => !w)} className="rounded-md border border-border bg-card px-2 py-1 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" > {wide ? "Normal letter spacing" : "Wide letter spacing"} </button> <ExpandableText maxLines={2} measureKey={wide} contentClassName={wide ? "tracking-[0.4em]" : undefined}> <span>{SHORT_EN} Two lines at normal spacing.</span> </ExpandableText> </div> );} export default function ExpandableTextDemo() { return ( <Tabs defaultValue="default"> <SwipeTabsList> <TabsTrigger value="default">Default</TabsTrigger> <TabsTrigger value="custom-lines">Custom maxLines</TabsTrigger> <TabsTrigger value="localized">Localized (TR)</TabsTrigger> <TabsTrigger value="rich">Rich children</TabsTrigger> <TabsTrigger value="rtl">RTL</TabsTrigger> <TabsTrigger value="custom-toggle">Custom toggle</TabsTrigger> </SwipeTabsList> <TabsContent value="default" className="mt-6 space-y-6"> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Long content (toggle appears) </p> <ExpandableText content={LONG_EN} /> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Short content (no toggle — content fits) </p> <ExpandableText content={SHORT_EN} /> </div> </TabsContent> <TabsContent value="custom-lines" className="mt-6 space-y-6"> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> maxLines=2 </p> <ExpandableText content={LONG_EN} maxLines={2} /> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> maxLines=6 </p> <ExpandableText content={LONG_EN} maxLines={6} /> </div> </TabsContent> <TabsContent value="localized" className="mt-6 space-y-6"> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Long content + Turkish labels </p> <ExpandableText content={LONG_TR} labels={TR_LABELS} /> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Short content + Turkish labels (no toggle rendered) </p> <ExpandableText content={SHORT_TR} labels={TR_LABELS} /> </div> </TabsContent> <TabsContent value="rich" className="mt-6 space-y-6"> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> children — your own mention / link renderer inside the clamp </p> <RichBody /> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Block children — one paragraph each, still held to maxLines </p> <ExpandableText maxLines={3}> <p>{SHORT_EN}</p> <p>{LONG_EN}</p> </ExpandableText> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Content that grows while clamped (re-measured) </p> <GrowingBody /> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> measureKey — re-measure on a style change (letter spacing) </p> <MeasureKeyBody /> </div> </TabsContent> <TabsContent value="rtl" className="mt-6 space-y-6"> <div dir="rtl" lang="ar" className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> An RTL page </p> <ExpandableText content={LONG_AR} labels={AR_LABELS} /> </div> <div className="space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Arabic post in an LTR feed — dir="auto" starts it at the right </p> <ExpandableText content={SHORT_AR} /> <ExpandableText content={SHORT_EN} /> </div> </TabsContent> <TabsContent value="custom-toggle" className="mt-6 space-y-2"> <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> Chevron-icon toggle via renderToggle slot (controlled mode) </p> <CustomToggleDemo /> </TabsContent> </Tabs> );} Usage
When to use
Reach for ExpandableText for any user-authored multi-line text where the surface budget is bounded — post bodies, comment bodies, event descriptions, news excerpts in feeds, profile bios. Pure CSS line-clamp clips silently; this component measures scrollHeight against lineHeight × maxLinesafter mount and on resize, so the "show more" toggle only appears when content actually exceeds the budget. Links and mentions go in as children (your own safe renderer). For editing or HTML / Plate JSON / Markdown documents, use rich-text-editor.
Rich children (links, mentions)
children wins over content and renders in a <div>, so block children are valid. Changes inside it are re-measured automatically (MutationObserver); pass measureKey for a change that alters no DOM (a web font finishing loading). Keyboard focus moving onto a link below the clamp expands the text (controlled: onExpandedChange(true)), so focus never lands on hidden text.
<ExpandableText maxLines={3} measureKey={post.updatedAt}>
<MentionText content={post.content} mentions={post.mentions} />
</ExpandableText>Direction
The text element has dir="auto" by default, so an Arabic post in an LTR feed starts at the right. Pass dir="ltr" / "rtl" to force one.
Upgrading to 0.3.0
- The text is clamped from the first paint (the server cannot measure), so there is no full-text flash and layout shift on hydration; the toggle still appears only when the text is truncated.
dir="auto"on the text element (was none).contentis optional; nothing renders only when there is neither content nor children.DEFAULT_EXPANDABLE_TEXT_LABELS→defaultExpandableTextLabels(alias kept); anundefinedlabel keeps its default.
Basic example
import { ExpandableText } from "@/components/expandable-text";
export function Example() {
return <ExpandableText content={post.body} />;
}Custom maxLines
<ExpandableText content={comment.body} maxLines={4} />Controlled mode (feed virtualization)
For virtualized feeds where posts unmount on scroll, persist the expand state in a host-level map so it survives re-mount.
const expandedSet = useExpandedSet(); // host's per-post state map
<ExpandableText
content={post.body}
expanded={expandedSet.has(post.id)}
onExpandedChange={(next) => expandedSet.toggle(post.id, next)}
/>Localized labels
<ExpandableText
content={post.body}
labels={{
showMore: "Daha fazla göster",
showLess: "Daha az göster",
}}
/>Custom toggle (chevron icon)
The renderToggle slot replaces the default text button. Receives isExpanded + setExpanded; consumers wire their own UI but should preserve aria-expanded + aria-label for accessibility.
import { ChevronDown, ChevronUp } from "lucide-react";
<ExpandableText
content={comment.body}
maxLines={2}
renderToggle={({ isExpanded, setExpanded }) => (
<button
type="button"
onClick={() => setExpanded(!isExpanded)}
aria-expanded={isExpanded}
aria-label={isExpanded ? "Collapse" : "Expand"}
>
{isExpanded ? <ChevronUp /> : <ChevronDown />}
</button>
)}
/>Standalone hook (advanced)
useLineClampDetectis exported for hosts that want to detect truncation without using our component (e.g., to show a small "..." indicator in a different style). The content parameter is typed unknown — pass any primitive or stable identity that changes when re-measurement is needed.
import { useLineClampDetect } from "@/components/expandable-text";
function MyTextBlock({ text }: { text: string }) {
const { ref, isTruncated } = useLineClampDetect({
maxLines: 3,
content: text,
});
return (
<div>
<p ref={ref} className="line-clamp-3">{text}</p>
{isTruncated && <span>...</span>}
</div>
);
}Anti-patterns
- Don't pass untrusted HTML as children — render links / mentions with your own safe components. Use
rich-text-editorfor Markdown / Plate JSON / HTML documents. - Don't expect auto-collapse on click outside — one-shot expand; user collapses by clicking the toggle.
- Don't expect animated height transition on expand/collapse — the swap is instant. Animation requires extra browser support and is not implemented.
- Don't define inline labels objects if you care about
React.memo— the inline object identity changes every render, busting memo. Hoist the labels object to module scope.
Accessibility
- Default toggle is a real
<button type="button">— keyboard activation via Enter / Space comes free. aria-expandedon the toggle reflects state;aria-controlslinks to the content'sid(computed viauseId).- Custom
renderToggleis the consumer's responsibility — preservearia-expanded+aria-labelon icon-only triggers.
Features
- Measure-based truncation detection — toggle hidden when content fits
- Rich children (your own link / mention renderer) inside the clamp, rendered in a <div>; plain `content` stays a <p>
- Re-measure on content / measureKey / maxLines change, on container resize (ResizeObserver) and on DOM changes inside rich children (MutationObserver)
- Clamped from the first paint — no full-text flash or layout shift on hydration
- dir="auto" on the text by default (bidi isolation), overridable
- Configurable maxLines (default 3)
- Controlled-or-uncontrolled expand state via expanded / defaultExpanded / onExpandedChange (the prop wins every render)
- Keyboard focus moving onto hidden content below the clamp expands it (controlled: asks)
- i18n via labels object (English defaults: 'Show more' / 'Show less'; an undefined key keeps its default)
- renderToggle slot for full toggle takeover
- Public useLineClampDetect hook export (optional observeMutations; line-height: normal handled)
- a11y: real <button> with aria-expanded + aria-controls; content id from useId; focus-visible ring
- Empty guard — renders nothing when there is neither content nor renderable children
- No peer deps beyond React