Skip to content

ShowHideLabel: Collapse button disappears when initialized expanded with short text #7270

Description

@unlikelyzero

ShowHideLabel renders a Collapse button that disappears the moment you click it, when it's initialized already-expanded with text that doesn't actually need truncating.

Repro

<ShowHideLabel show={true} maxChars={256}>Short message</ShowHideLabel>

Text is shorter than maxChars, so no truncation is ever needed — but a Collapse button still renders, because needsButton is computed like this:

const [actualText, needsButton] = React.useMemo(() => {
  if (typeof children !== 'string') {
    return ['', false];
  }

  if (expanded) {
    return [children, true];
  }

  return [children.substr(0, maxChars), children.length > maxChars];
}, [children, expanded, maxChars]);

When expanded is true (from show={true}), needsButton is unconditionally true, regardless of whether the text is actually long enough to need a toggle. Clicking the rendered Collapse button flips expanded to false, which recomputes needsButton as children.length > maxCharsfalse for short text — so the button vanishes entirely rather than toggling back to an Expand button. The control disappears rather than behaving like a toggle.

Fix

needsButton should depend only on whether the text actually exceeds maxChars, independent of expanded:

const isLong = typeof children === 'string' && children.length > maxChars;
const actualText = expanded || !isLong ? children : children.slice(0, maxChars);
return [actualText, isLong];

Where I found this

Ran into this while reviewing #7267, which touches this same component's DOM structure for an aria-attribute fix but doesn't touch this logic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions