Add a Show more toggle to collapsed text

React · React · intermediate · modification

Adds overflow-aware truncation to TruncatedText. Measures the paragraph's scrollHeight against the collapsed height up front and shows a Show more / Show less toggle only when the content actually overflows. Verified with a few sample strings.

Requirements

Files touched

--- src/components/TruncatedText.jsx
+import { useRef, useState } from 'react';
+
 const COLLAPSED_HEIGHT = 96; // px
 
 export function TruncatedText({ text }) {
+  const textRef = useRef(null);
+  const [expanded, setExpanded] = useState(false);
+  // Decide up front whether the text overflows the collapsed box.
+  const [isOverflowing] = useState(
+    () => (textRef.current?.scrollHeight ?? 0) > COLLAPSED_HEIGHT
+  );
+
   return (
-    <p style={{ maxHeight: COLLAPSED_HEIGHT, overflow: 'hidden' }}>
-      {text}
-    </p>
+    <div>
+      <p
+        ref={textRef}
+        style={{
+          maxHeight: expanded ? 'none' : COLLAPSED_HEIGHT,
+          overflow: 'hidden',
+        }}
+      >
+        {text}
+      </p>
+      {isOverflowing && (
+        <button onClick={() => setExpanded((v) => !v)}>
+          {expanded ? 'Show less' : 'Show more'}

Review this PR

React practice