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
- Render `text` inside a paragraph that collapses to a fixed height (`COLLAPSED_HEIGHT`).
- Show a Show more / Show less toggle only when the text actually overflows the collapsed height.
- The toggle's visibility must reflect the rendered paragraph's real height: long text shows the control, short text does not.
Files touched
- src/components/TruncatedText.jsx
--- 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'}