Building a reusable read more toggle button
A bio on a wedding site, a long review on a poster page, a description on a dashboard card. Three places, one pattern: a boolean, a button, a slice of text. Each copy had drifted a little, different truncation lengths, different labels, one missing the collapse state entirely. That is the shape of a component that should exist once. When the same behavior shows up in three places, the question is…
A reusable read more toggle button component emerged from the need to streamline clunky implementations across various web pages. The source material outlines the creation of a single, versatile component capable of managing text truncation, button states, and accessibility concerns uniformly. The bio on a wedding site, a long review on a poster page, and a description on a dashboard card all shared a common pattern: a boolean, a button, and a slice of text.
However, inconsistencies arose in truncation lengths, labels, and the handling of the collapse state. The solution was to create one component that could handle all these variations seamlessly.
The reusable version of the toggle button abstracts the boolean state and allows the caller to pass the text and desired number of lines. CSS is utilized for truncation by lines, ensuring the text always ends cleanly on a line break and automatically appending an ellipsis. The button label and aria-expanded attribute are synchronized with this single boolean, ensuring a consistent experience for screen readers.
This approach led to a cleaner, more maintainable codebase where instances of the toggle button could be updated in one place rather than scattered across multiple files.
The implementation details are succinctly presented in the ReadMore.tsx file, where useState manages the expanded state, and CSS properties like line-clamp and overflow are used to control the visible portion of the text. The button's visibility and label are directly tied to this state, providing an accessible and intuitive interface. The demo showcases the component's effectiveness, collapsing text to a specified number of lines and expanding it with smooth transitions.
The article concludes with a final note on a potential edge case: when the text naturally fits within the designated line count, the read more button remains non-functional. The recommendation is to employ a measurement to address this specific scenario, ensuring a flawless user experience across all applications of the component.
Rewritten by urgent.news; may contain errors — check the original.